【问题标题】:Searching for a superview inside UITableViewCell iOS7在 UITableViewCell iOS7 中搜索超级视图
【发布时间】:2013-09-26 08:39:34
【问题描述】:

我有一个名为EditableTableViewCell 的自定义UItableViewCell 类(除其他内容外)在其contentView 中添加了一个UITextField。在Textfield 委托方法中,我试图检测它属于哪个部分。像这样:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    UIView* contentView =[textField superview];
    //traverse up in the view hierarchy until we find the cell's content view.
    while (![contentView isKindOfClass:[EditableTableViewCell class]] || contentView.superview == nil) {
        contentView = [contentView superview];
    }
    EditableTableViewCell *thiscell = (EditableTableViewCell*)contentView;
    NSIndexPath *indexpath =[[self tableView]indexPathForRowAtPoint:thiscell.center];

这给了我正确的结果,我看到了类似的解决方案 here 也导航视图层次结构。我想知道这是否是唯一的解决方案,或者是否有更合适的方法不涉及循环所有可用单元格。

【问题讨论】:

    标签: ios uitableview ios7


    【解决方案1】:

    试试这个,不需要循环遍历视图

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
        UIView* contentView =[textField superview];
        CGPoint center = [self.tableView convertPoint:textField.center fromView:contentView];
        NSIndexPath *indexpath =[[self tableView] indexPathForRowAtPoint:center];
        NSLog(@"indexPath:%@", indexpath);
    }
    

    【讨论】:

    • 你应该把@放在NSLog之前。我尝试编辑它,但它不允许我。这有效,但我不知道它是否更有效,因为我的实现也有效。你知道如何测试吗?
    • 是的,谢谢,只需编辑代码。 "c string" 是 C 字符串,但不是 NSString,对此我很抱歉
    • 我的代码应该更通用,而你的代码依赖于EditableTableViewCell,
    【解决方案2】:

    为什么不

    NSIndexPath *indexpath = [(UITableView*)self.superview indexPathForCell:self]
    

    ?

    【讨论】:

    • 好吧,因为在 iOS7 之前,像 textfield.superview.superview 这样的单元格被发现;否则 indexpath 总是返回 0
    • .superview 对我来说是一种代码味道。 .superview.superview 真的很臭。我正在处理的一个项目有很多这样的问题,现在它在 iOS 7 中被破坏了。它闻起来像一个问题,最终成为一个问题。总有比做 .superview 更好的方法,就是懒惰。
    • 文本视图的代理是哪个对象?单元格本身还是视图控制器?
    • @bandejapaisa 我同意。问题中的设计不好。
    • @bandejapaisa 我也认为不好,但另一种选择是标签,我也不太喜欢标签,特别是创建和删除的 tableviewcells。顺便说一句,昵称不错 ;) la bandeja paisa 规则!
    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多