【问题标题】:subviews userinteraction when superview userinteraction disabled swift快速禁用超级视图用户交互时的子视图用户交互
【发布时间】:2016-09-26 07:20:18
【问题描述】:

我想保持子视图(在这种情况下为 UITextFields)仍然处于活动状态(以通常的方式可编辑,即点击 textField 并出现键盘),而作为 UITableViewCell 的 userInteractionEnabled 的父视图设置为 false。

进一步解释 - 1.有一个从xib初始化的UITableViewCell。

  1. 在这个单元格内,我有三个 UITextField 和一个 UIButton。
  2. 在某些情况下,我需要禁用单元格交互(以避免 didSelectRowAtIndexPath) - 这部分我没有任何问题。
  3. 在第 3 步之后,单元格内的所有子视图也将被禁用。
  4. 但我需要在 textFields 中输入一些文本,然后点击按钮进行一些操作。

到目前为止我做了什么: 1. 使用 userInteractionEnabled 并将其设置为单元格的 false -

myPersonalInfoExpandedCell.userInteractionEnabled = false

2。两个 textFields firstNameText 和 lastNameText,我启用了 userInteraction 并将 firstNameText 设置为 becomeFirstResponder

 (myPersonalInfoExpandedCell as! PersonalInfoExpandedCell).firstNameText.userInteractionEnabled = true
 (myPersonalInfoExpandedCell as! PersonalInfoExpandedCell).lastNameText.userInteractionEnabled = true
 (myPersonalInfoExpandedCell as! PersonalInfoExpandedCell).firstNameText.becomeFirstResponder()

问题是,对于 textFields,userInteractionEnabled 不起作用,我怀疑这是因为 userInteractionEnabled 对于 TableViewCell 是错误的。 becomeFirstResponder() 正在为 firstNameText 工作,但我需要与单元格内的所有 UI 元素进行交互。

我们怎样才能做到这一点?请问有人可以帮忙吗?

【问题讨论】:

    标签: ios iphone swift cocoa-touch


    【解决方案1】:

    要禁用 cellSelection,请实现 willSelectRowAtIndexPath 委托方法,并为您不想选择的单元格返回 nil。你说你想在某些条件下禁用选择,所以我假设你有你想要禁用选择的行的 indexPaths。只需为这些 indexPaths 返回 nil。请参阅以下代码。

    -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
    if (indexPath == self.MyIndex) //Check for the index path for the cell you want to disable selection for
       return nil;
    else
       return indexPath;
    }
    

    这样做也可以防止单元格突出显示。

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    

    这样做您不必在单元格上设置UserInteractionEnabled:NO。这样,当您点击单元格时,不会调用 didSelectRowAtIndexPath 委托方法,并且您的 textFields 仍将启用

    编辑

    以下是上述代码的 swift 版本

    func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    if (indexPath == self.MyIndex) //Check for the index path for the cell you want to disable selection for
        return nil;
    else
        return indexPath;
    }
    
    
    cell.selectionStyle = .None
    

    【讨论】:

    • 感谢沙燕的回答!为我不想选择的单元格返回 false?我没明白。可以举个例子吗?
    • @LohithKorupolu 我已经编辑了我的答案。看看它。如果您仍有疑问,请随时提出
    • 它工作正常,我可以编辑我的文本字段,但我的 UIButton 在同一个视图中出现问题。当我点击按钮时,我得到一个异常 libc++abi.dylib: terminating with uncaught exception of type NSException
    • stackoverflow.com/questions/26442414/… 查看此链接。这很可能是您的 IBOutlet 的问题。删除所有连接并重新添加它们
    • 是的,我已经看过了。但也许我应该删除连接并重新添加它们。但是对于实际的答案,我接受它:-)
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2020-01-16
    • 2020-01-13
    • 2015-06-06
    • 1970-01-01
    • 2011-12-14
    • 2015-06-25
    • 2019-10-13
    相关资源
    最近更新 更多