出队后,自定义UICollectionViewCell属性为空
所以我有一个UICollectionView和一个自定义的单元格,这一切都显示出来,工作很好。 我在viewDidLoad中注册类:
myCollectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:layout]; [myCollectionView setDataSource:self]; [myCollectionView setDelegate:self]; [myCollectionView setBackgroundColor:[UIColor myColor]]; [myCollectionView registerClass:[SBCustomCell class] forCellWithReuseIdentifier:@"Cell"];
在我的cellForItemAtIndexPath方法中,我将这个单元格出队并设置它的属性并返回它:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"Cell"; SBCustomCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; [cell setName: "My Name"]; cell.image = [UIImage imageNamed:@"lol.png"]; cell.score = 100.0; cell.backgroundColor=[UIColor whiteColor]; return cell; }
这一切工作正常,它显示在用户界面。 我的问题是,当我在collectionView上设置一个手势识别器,当我长按某个单元格时,我想能够访问它的属性。 我试图这样做:
-(void)handleLongPress:(UILongPressGestureRecognizer *)longPressRecognizer { CGPoint locationPoint = [longPressRecognizer locationInView:myCollectionView]; if (longPressRecognizer.state == UIGestureRecognizerStateBegan) { NSIndexPath *indexPathOfMovingCell = [myCollectionView indexPathForItemAtPoint:locationPoint]; SBCustomCell *cell= [myCollectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPathOfMovingCell]; NSLog(@"%@",cell.name);
当我尝试访问我的自定义单元格的任何属性时,它在控制台(空)。 这是为什么? 我究竟做错了什么?
你需要使用:
SBCustomCell* cell = (SBCustomCell*)[myCollectionView cellForItemAtIndexPath:indexPathOfMovingCell];
代替:
SBCustomCell* cell = [myCollectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPathOfMovingCell];
此外,您正在使用SBSingleCandidateUnitView
而不是您的SBCustomCell
的单元格types。
这是因为我没有正确设置我的属性。 在我的头文件中,我需要设置一个属性,又名@property … UIImageView myImageView;
在我的CustomCell.m文件中,我不应该重写这些setter和getters。 而只是分配和启动它们并将它们添加到视图中。
回到我的ViewController.m中,我应该添加这样的属性:
customcell.myImageView.image = [UIImage imageNamed:@“cartman.png”];