将UITextfield聚焦在自定义单元格中

时间:2017-05-23 16:02:55

标签: ios swift uitableview uitextfield custom-cell

我在自定义单元格中有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
}

1 个答案:

答案 0 :(得分:1)

问题是,你有多个单元格,并且每当他们被抽出时都会指示他们becomeFirstResponder

如果您想在显示表格时仅在第一个单元格上设置焦点,并且只有那时,您可以在UITextField时标记indexPath.row == 0,在viewDidAppear中标记为简单获取带标记的字段并设置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)
}