以编程方式将UIButton添加到UICollectionView单元

时间:2013-07-24 19:47:17

标签: 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;
}

我做错了什么?

1 个答案:

答案 0 :(得分:5)

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