以编程方式将 UIButton 添加到 UICollectionView 单元格 [英] Adding a UIButton to a UICollectionView cell programmatically

查看:25
本文介绍了以编程方式将 UIButton 添加到 UICollectionView 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a UIViewController with a UICollectionView created inside it programmatically. I want to add a button to the cell:

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 的子视图.另外,不要在每次调用 collectionView:cellForItemAtIndexPath: 时都创建按钮.您可能正在重用已有按钮的现有单元格.最好在自定义单元格的 init 方法中添加按钮.然后在不需要时隐藏按钮.

Add your button as a subview of cell.contentView. Also, don't create the button every time collectionView:cellForItemAtIndexPath: is called. You might be reusing an existing cell that already has a button. Better to add the button in your custom cell's init method instead. Then just hide the button when you don't need it.

这篇关于以编程方式将 UIButton 添加到 UICollectionView 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆