即使设置了委托

时间:2015-09-21 20:47:37

标签: ios objective-c uicollectionviewcell

我只是想在UICollectionView内做一个简单的香草UIViewController。一切都按预期工作,只是当我触摸CollectionViewCell选择它时没有任何反应。这是我的代码的骨头:

@interface CreateNewFieldViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

- (void) viewDidLoad {
...
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(self.width*.15, self.width*.15);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    flowLayout.minimumInteritemSpacing = 30;
    flowLayout.minimumLineSpacing = 30;   

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(self.width*.1, self.height*.2, self.width*.8, self.height*.3) collectionViewLayout:flowLayout];

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;

    self.collectionView.allowsSelection = YES;
    self.collectionView.allowsMultipleSelection = NO;

    self.collectionView.bounces = YES;
    self.collectionView.alwaysBounceHorizontal = YES;
    self.collectionView.alwaysBounceVertical = YES;
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:self.collectionView];

    self.collectionView.backgroundColor = [UIColor clearColor];
...
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.fieldNameInput.text = self.backgroundImageNames[indexPath.row];
    NSLog(@"recording this: %@", self.fieldNameInput.text);
}

数据源和流布局工作得很好,但出于某种原因,当我点击一个单元格时,什么也没发生。我没有看到任何日志语句,所以我知道didSelect没有被调用。我错过了什么?

看起来这可能是一个不知情的陷阱,虽然我仍然无法找到它是什么。参见例如这blog post

1 个答案:

答案 0 :(得分:1)

对UICollectionView的额外调用解决了这个问题:

[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.selected = YES;
    [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    return cell;
}