故事板亲子关系不代表“superview”返回的内容

我在集合视图中有这个布局

集合视图单元格按以下方式分类:

在这里输入图像说明

我在集合视图中有这个布局。 在创build每个button时,我会调用以下代码:

[cell.imageButton addTarget:self action:@selector(galleryImageButtonClicked:event:) forControlEvents:UIControlEventTouchUpOutside]; 

哪个叫这个:

  -(void)galleryImageButtonClicked:(id)sender event:(id)event { if ([sender isKindOfClass:[UIButton class]]) { NSLog(@"Yay, it's a UIButton."); SCCollectionViewCell* parentCellOfThisButton = (SCCollectionViewCell*)[sender superview]; if ([parentCellOfThisButton isKindOfClass:[SCCollectionViewCell class]]) { UICollectionView *parentCollectionView = (UICollectionView* )[parentCellOfThisButton superview]; if ([parentCollectionView isKindOfClass:[UICollectionView class]]) { NSIndexPath* indexPathOfCell = [parentCollectionView indexPathForCell:parentCellOfThisButton]; } else { NSLog(@"Not a UIcollectionClass"); } } else { NSLog(@"ERROR! 15268679"); } } } 

这就失败了:

  if ([parentCellOfThisButton isKindOfClass:[SCCollectionViewCell class]]) 

有谁知道为什么?

为了工作,代码需要知道button位于单元的视图层次结构中的哪个位置。 编写一个更普遍地查找button的单元格的方法可能会更好,如下所示:

 - (UICollectionViewCell *)cellContainingSubview:(UIView *)view { while (view && ![view isKindOfClass:[UICollectionViewCell self]]) { view = [view superview]; } return view; } 

然后在你的button方法中,不需要检查发送者是否是一个button(只有button调用这个select器,对吗?)。 获取像这样的包含单元格:

 SCCollectionViewCell* parentCellOfThisButton = (SCCollectionViewCell*)[self cellContainingSubview:sender]; 

请注意,如果您知道只有SCCollectionViewCells包含使用此方法的button,则强制转换才是正确的。

它失败了,因为UICollectionViewCell的内部实现使用比类接口中描述的视图更复杂的一组视图。

而不是让你的button试图找出谁叫它,为什么,重写你的代码,让button被告知该怎么做。 例如,你可以指定一个不同的select器,这取决于这个特定的button应该做什么。