objective-c - 以编程方式将 UIButton 添加到 UICollectionView 单元格

标签 objective-c uiviewcontroller uicollectionview uicollectionviewcell

我有一个 UIViewController,其中以编程方式在其中创建了一个 UICollectionView。我想在单元格中添加一个按钮:

viewDidLoad:

UICollectionViewLayout *layout = [[UICollectionViewFlowLayout alloc]init];
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];

    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[EMCell class] forCellWithReuseIdentifier:@"Cell"];

    [self.view addSubview:_collectionView];

然后:

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

    cell.backgroundColor = [UIColor greenColor];

    UIButton *button = (UIButton *)[cell viewWithTag:200];
    [button setFrame:CGRectMake(10, 10, 50, 60)];
    [button setTitle:@"Button" forState:UIControlStateNormal];

    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [cell addSubview:button];
    return cell;
}

我做错了什么?

最佳答案

将您的按钮添加为 cell.contentView 的 subview 。另外,不要在每次调用 collectionView:cellForItemAtIndexPath: 时都创建按钮。您可能正在重复使用已有按钮的现有单元格。最好改为在自定义单元格的 init 方法中添加按钮。然后在不需要时隐藏按钮即可。

关于objective-c - 以编程方式将 UIButton 添加到 UICollectionView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843533/

相关文章:

ios - 自定义 UICollectionViewFlowLayout 问题

iphone - 如何确定为 Web 服务 API 实现的 Http 方法类型

objective-c 运行时委托(delegate)问题

ios - 需要有关使用核心位置计算距离的帮助

ios - 在 View 之间保留 UITextField 中的文本

ios - UICollectionView 高度不能使用内部 UIScrollView 动态递增

ios - 创建和插入数组对象时出错

ios - cocoa : Can't remove child view controller

ios - 从一个 VC 切换到另一个时在 View Controller 中保留数据

ios - 没有调用 prepareForSegue 的 UITableView 到 UICollectionView