ios - 在 iOS 7 中使用 superview 获取 UITableViewCell

标签 ios objective-c superview

我正在获取 UIButton 所属的 UITableViewCell,如下所示:

-(void)buttonHandler:(UIButton *)button {

    OrderCell *cell = [[button superview] superview];
    NSLog(@"cell.item = %@", cell.item.text);

它在 iOS 7 之前的任何系统中都运行良好。但是给了我:

[UITableViewCellScrollView item]: 无法识别的选择器发送到实例 0x17ae2cf0

如果我在 iOS 7 中运行该应用程序。但是如果我这样做:

-(void)buttonHandler:(UIButton *)button {

    OrderCell *cell = [[[button superview] superview] superview];
    NSLog(@"cell.item = %@", cell.item.text);

那么它可以在 iOS 7 中使用,但不能在更早的版本中使用?!?!?!

我通过这样做来规避这个问题:

OrderCell *cell;
if([[[UIDevice currentDevice] systemVersion] isEqualToString:@"7.0"])
    cell = [[[button superview] superview] superview];
else
    cell = [[button superview] superview];

NSLog(@"cell.item = %@", cell.item.text);

但是 WTF 还在继续!? 有谁知道为什么会这样?

谢谢!

最佳答案

更好的解决方案是为 UIView(SuperView) 添加一个类别,并通过以下方式调用它:

UITableViewCell *cell = [button findSuperViewWithClass:[UITableViewCell class]]

这样,您的代码适用于所有 future 和过去的 iOS 版本

@interface UIView (SuperView)

- (UIView *)findSuperViewWithClass:(Class)superViewClass;

@end


@implementation UIView (SuperView)

- (UIView *)findSuperViewWithClass:(Class)superViewClass {

    UIView *superView = self.superview;
    UIView *foundSuperView = nil;

    while (nil != superView && nil == foundSuperView) {
        if ([superView isKindOfClass:superViewClass]) {
            foundSuperView = superView;
        } else {
            superView = superView.superview;
        }
    }
    return foundSuperView;
}
@end

关于ios - 在 iOS 7 中使用 superview 获取 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962771/

相关文章:

php - JPEG 图像在 Android 和 IOS 后端 php webservice 中显示不同

ios - 如何为多个客户维护一个自定义 B2B iOS 应用程序

iphone - 使用自定义 tableview 单元格中的按钮删除行

iphone - removeFromSuperview 导致我的应用程序崩溃

iOS - 界面布局

iphone - TableView 在推送 Controller 并将其弹出时不会重新加载数据?

objective-c - CALayer setContents 不适用于 10.5

objective-c - 多任务手势不适用于警报

objective-c - 使用表示变量名称的字符串来设置变量