我得到的UITutView属于这样的UITutViewCell:
-(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还在继续!? 有谁知道为什么会这样?
谢谢!
答案 0 :(得分:27)
更好的解决方案是为UIView(SuperView)添加一个类别,并通过以下方式调用它:
UITableViewCell *cell = [button findSuperViewWithClass:[UITableViewCell class]]
这样,您的代码适用于所有未来和过去的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
答案 1 :(得分:13)
最好的方法是:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
UITableViewCell *cell = (UITableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
答案 2 :(得分:3)
要完成 @ thomas-keuleers 的答案,这是一个快速的方法:
extension UIView {
func findSuperViewWithClass<T>(superViewClass : T.Type) -> UIView? {
var xsuperView : UIView! = self.superview!
var foundSuperView : UIView!
while (xsuperView != nil && foundSuperView == nil) {
if xsuperView.self is T {
foundSuperView = xsuperView
} else {
xsuperView = xsuperView.superview
}
}
return foundSuperView
}
}
你只需这样打电话:
child.findSuperViewWithClass(TableViewCell)
答案 3 :(得分:0)
快速版本5中的较短版本
extension UIView {
var xsuperView = self.superview
while xsuperView != nil {
if let superView = xsuperView.self as? T {
return superView
} else {
xsuperView = xsuperView?.superview
}
}
}
答案 4 :(得分:-2)
if ([[button superView] isKindOfClass:[UITableViewCell class]]) {
}
else //check next :