xcode 以编程方式将按钮添加到集合视图单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15821486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically Adding Button To Collection View Cell
提问by jac300
I have an application in Xcode 4.6. In one view controller I have a collection view. Cells are added to the view via user interaction with the view. This works fine. I then wanted to add a button (programmatically) to each cell which allows the cell to be deleted. I wanted the button to be located at the top right corner of each cell. The problem is that the button appears in the desired spot within each cell for all cells in the first row of the collection view, (again, top right), but then appears outside of cells for all cells after the first row. See image below:
我在 Xcode 4.6 中有一个应用程序。在一个视图控制器中,我有一个集合视图。单元格通过用户与视图的交互添加到视图中。这工作正常。然后我想向每个单元格添加一个按钮(以编程方式),允许删除该单元格。我希望按钮位于每个单元格的右上角。问题是按钮出现在集合视图第一行中所有单元格的每个单元格内的所需位置(再次,右上角),但随后出现在第一行之后所有单元格的单元格之外。见下图:
My button creation method is:
我的按钮创建方法是:
-(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;
}
}
The above method is called in my cell creation method as follows:
上述方法在我的单元格创建方法中调用如下:
-(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;
}
Can anyone suggest what I might be doing wrong?
谁能建议我可能做错了什么?
采纳答案by vacawama
The button is added as a subview of the cell. It should be using the coordinate system of the cell (bounds) and not the coordinate system of the cell's superview (frame). In your case, since the button is to be at the top of the cell set
该按钮被添加为单元格的子视图。它应该使用单元格(边界)的坐标系,而不是单元格超级视图(框架)的坐标系。在您的情况下,由于按钮将位于单元格集的顶部
CGFloat Y = 0;