您好:我已经在iOS 6,7和现在8(测试版5)上测试了我的应用。我的UITableView
自定义UITableViewCell
在6和7上工作正常。但是,在iOS 8上,当我尝试访问单元格的子视图(文本字段)时,我遇到了崩溃
我知道在iOS 7的单元格层次结构中还有另一个视图这一事实。奇怪的是,iOS 8中的情况似乎并非如此。'我使用的代码:
//Get the cell
CustomCell *cell = nil;
//NOTE: GradingTableViewCell > UITableViewCellScrollView (iOS 7+ ONLY) > UITableViewCellContentView > UIButton (sender)
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
cell = (CustomCell *)sender.superview.superview;
} else {
cell = (CustomCell *)sender.superview.superview.superview;
}
//Get the cell's index path
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//etc.
NSLog(@"%@", cell.textField); //<---Crashes here
因此,正如您所看到的,我在iOS 7中考虑了额外的视图。在添加了一些断点并仔细查看变量后,我发现cell
存在,但所有它在界面文件中的子视图(已链接) - 包括textField
- 是nil
。在指定的行,我收到以下崩溃日志:
-[UITableViewWrapperView textField]: unrecognized selector sent to instance 0x12c651430
我进一步研究了这个,我发现了这个:
将else
语句更改为与上一行相同可以解决崩溃问题,并且应用程序正常运行(使用iOS 6中的sender.superview.superview
)。
这让我觉得毫无意义。 Apple是否将UITableViewCell
的层次结构恢复为iOS 6的层次结构,或者我错过了什么?谢谢!
答案 0 :(得分:9)
我遇到了同样的问题。这是一种更可靠的方法:
UITextField* textField = (UITextField*)sender;
NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:[self.tableView convertPoint:textField.center fromView:textField.superview]];
无论UITableViewCell的基础视图层次结构如何,这都将起作用。
答案 1 :(得分:6)
不同的iO版本具有UITableView
或UITableViewController
的不同实现,作为一个简单的修复,您必须遍历superviews
,直到找到所需的视图类而不是依赖它第N次超级视图。
答案 2 :(得分:1)
我在iOS8上也遇到了同样的问题,从子视图通过superview获取UITableViewCell。这就是我对iOS7和iOS8支持的想法。
-(void)thumbTapped:(UITapGestureRecognizer*)recognizer {
NSLog(@"Image inside a tableview cell is tapped.");
UIImageView *mediaThumb = (UIImageView*)recognizer.view;
UITableViewCell* cell;
// get the index of container cell's row
// bug with ios7 vs ios8 with superview level!! :(
/*** For your situation the level of superview will depend on the design structure ***/
// The rule of thumb is for ios7 it need an extra superview
if (SYSTEM_VERSION_LESS_THAN(@"8.0")) { // iOS 7
cell = (UITableViewCell*)mediaThumb.superview.superview.superview.superview;
} else { // iOS 8
cell = (UITableViewCell*)mediaThumb.superview.superview.superview;
}
}
为了澄清,在cellForRowAtIndexPath中,我分配了点击手势识别器。故事板中的原始设计非常复杂,有许多子视图,按钮等等。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MediaCell" forIndexPath:indexPath];
.......
UIImageView *mediaImage = ............
.....................................
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(thumbTapped:)];
[mediaImage addGestureRecognizer:tapGestureRecognizer];
return cell;
}