【问题标题】:Focus UITextfield in Custom cell在自定义单元格中聚焦 UITextfield
【发布时间】:2017-05-23 16:02:54
【问题描述】:

我在自定义单元格中有 2 个UITextfield。现在我想在从其他视图推送时将焦点设置在第一个文本字段上。

这是我在 cellForRowAt 委托中的代码,但这不起作用:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let userCell = tableView.dequeueReusableCell(withIdentifier: "InputUserInfoForm") as! InputUserInfoForm
        userCell.selectionStyle = .none

        userCell.fistnameTextField.autocorrectionType = .no
        userCell.lastnameTextField.autocorrectionType = .no

        // Firstname textfield
        userCell.fistnameTextField.tag = RegisterForm.Firstname.rawValue
        userCell.firstnameLabel.text = "FirstnameTitle".localized()
        userCell.firstnameLabel.becomeFirstResponder()

        // Lastname textfield
        userCell.lastnameTextField.tag = RegisterForm.Lastname.rawValue
        userCell.lastnameLabel.text = "LastnameTitle".localized()

        return userCell
}

【问题讨论】:

  • 你为什么要把这段代码放在cellForRowAt?它似乎更适合viewDidAppear

标签: ios swift uitableview uitextfield custom-cell


【解决方案1】:

问题是,您有多个单元格,每次绘制它们时都会指示becomeFirstResponder

如果您只想在显示表格时将焦点设置在第一个单元格上,并且只有这样,您可以在 indexPath.row == 0viewDidAppear 中标记 UITextField,您只需使用标记获取该字段并设置becomeFirstResponder

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let userCell = tableView.dequeueReusableCell(withIdentifier: "InputUserInfoForm") as! InputUserInfoForm
    userCell.selectionStyle = .none

    userCell.fistnameTextField.autocorrectionType = .no
    userCell.lastnameTextField.autocorrectionType = .no

    // Firstname textfield
    userCell.fistnameTextField.tag = RegisterForm.Firstname.rawValue
    userCell.firstnameLabel.text = "FirstnameTitle".localized()
    if indexPath.row == 0 {
        userCell.firstnameLabel.tag = 123
    }

    // Lastname textfield
    userCell.lastnameTextField.tag = RegisterForm.Lastname.rawValue
    userCell.lastnameLabel.text = "LastnameTitle".localized()

    return userCell
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    self.view.viewWithTag(123)
}

【讨论】:

  • @ManhNguyen 我看到你是 stackoverflow 的新手。如果此答案解决了您的问题,请不要忘记将其标记为已接受。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多