Storyboard parent-child relationship not representing what is returned by “superview”

前提是你 提交于 2019-12-25 02:41:55

问题


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];

Which calls this:

    -(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");
    }
}
}

This fails on the line:

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

Does anyone know why?


回答1:


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];

Note that the cast is only okay if you know that only SCCollectionViewCells contain the buttons that use this method.




回答2:


It fails because the internal implementation of UICollectionViewCell uses a more complex set of views than described in the class's interface.

Instead of having your button try to figure out who called it and why, rewrite your code so the button is told what to do. For example, you could specify a different selector depending on what this particular button should be doing.



来源:https://stackoverflow.com/questions/20340714/storyboard-parent-child-relationship-not-representing-what-is-returned-by-super

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!