故事板父子关系不代表“超级视图"返回的内容 [英] Storyboard parent-child relationship not representing what is returned by "superview"
问题描述
Collection View Cell 子类化如下:
The Collection View Cell is subclassed in the following way:
我在集合视图中有这个布局.在创建每个按钮时,我调用以下代码:
I have this layout in a collection view. On each button when it is created, I call the following code:
[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]])
有人知道为什么吗?
推荐答案
为了工作,代码需要知道按钮在单元格视图层次结构中的位置.编写一个更一般地查找按钮单元格的方法可能会更好,如下所示:
To work, the code needs to know where in the cell's view hierarchy the button sits. It might be better to write a method that finds the button's cell more generally, like this:
- (UICollectionViewCell *)cellContainingSubview:(UIView *)view {
while (view && ![view isKindOfClass:[UICollectionViewCell self]]) {
view = [view superview];
}
return view;
}
然后在你的按钮方法中,没有必要检查发送者是否是一个按钮(只有按钮调用这个选择器,对吧?).像这样获取包含单元格:
Then in your button method, there's no need to check if the sender is a button (only the buttons invoke this selector, right?). Get the containing cell like this:
SCCollectionViewCell* parentCellOfThisButton = (SCCollectionViewCell*)[self cellContainingSubview:sender];
请注意,只有当您知道只有 SCCollectionViewCells 包含使用此方法的按钮时,才能进行转换.
Note that the cast is only okay if you know that only SCCollectionViewCells contain the buttons that use this method.
这篇关于故事板父子关系不代表“超级视图"返回的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!