5

我有一个 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;
}

我究竟做错了什么?

4

1 回答 1

5

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

于 2013-07-24T21:23:49.473 回答