本文介绍了以编程方式将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单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 18:01