1

我在Xcode 4.6中有一個應用程序。在一個視圖控制器中,我有一個集合視圖。通過用戶與視圖的交互,單元格被添加到視圖中。這工作正常。然後我想給每個單元添加一個按鈕(以編程方式),以便刪除單元。我希望按鈕位於每個單元格的右上角。問題是該按鈕出現在每個單元格中的集合視圖的第一行中的所有單元格(再次,右上角)中的所需點上,但是在第一行之後出現在單元格的所有單元格之外。見下圖:enter image description here以編程方式將按鈕添加到集合視圖單元格

我的按鈕,創建方法是:

-(CollectionViewCellButton *)makeDeleteButtonForCell:(UICollectionViewCell *)cell 
{ 
    CollectionViewCellButton *button = [CollectionViewCellButton buttonWithType:UIButtonTypeCustom]; 
    CGSize newImageSize = CGSizeMake(cell.frame.size.width/2.5, cell.frame.size.height/2.5); 
    UIImage *image = [SeeYourAlbumViewController imageWithImage:[UIImage imageNamed:@"delete"] scaledToSize:newImageSize]; 

    CGFloat width = image.size.width; 
    CGFloat height = image.size.height; 
    CGFloat X = cell.frame.size.width - width; 
    CGFloat Y = cell.frame.origin.y; 

    button.frame = CGRectMake(X, Y, width, height); 
    [button setImage:image forState:UIControlStateNormal]; 
    [button addTarget:self 
      action:@selector(deleteCollectionViewCell:) 
    forControlEvents:UIControlEventTouchUpInside]; 

    return button; 

}

上述方法被稱爲在我的小區創建方法如下:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
      cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView 
           dequeueReusableCellWithReuseIdentifier:@"newCell" 
           forIndexPath:indexPath]; 

    //CALLED HERE!! 
    CollectionViewCellButton *cellButton = [self makeDeleteButtonForCell:cell]; 

    cellButton.indexPath = indexPath; 
    [cell addSubview:[self.pictures objectAtIndex:indexPath.row]]; 
    [cell addSubview:cellButton]; 

    return cell; 
} 

任何人都可以提出我可能做錯了什麼?

回答

1

該按鈕被添加爲單元格的子視圖。它應該使用單元格的座標系(邊界),而不是單元格的超視圖(框架)的座標系統。在你的情況下,由於按鈕將位於單元組頂部

CGFloat Y = 0; 
相關問題