我正在获取 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/