【问题标题】:make textfield of cell that is not visible as first responder使单元格的文本字段作为第一响应者不可见
【发布时间】:2017-09-10 10:19:42
【问题描述】:

处理具有多个字段的登录表单。

当用户点击键盘的下一步/完成(默认按钮)按钮时,下一个文本字段应成为第一响应者。

TextFieldUITableViewCell 中。当用户点击 Done 按钮时,我会获取下一个单元格并将其文本字段作为第一响应者。但如果下一个单元格不可见,则下一个文本字段不会成为第一响应者。

如何解决这个问题?

func makeTextFieldFirstResponder(textField:UITextField) -> Bool {
    let row = textField.tag
    let indxPath = IndexPath(row: textField.tag + 1, section: 0)
    if let cell = tblEditViewDetail.cellForRow(at: indxPath) as? InputCell {
        cell.txtField.firstResponder()
    }
}

【问题讨论】:

  • 你的代码或屏幕截图可以在你卡住的地方吗
  • CellForRow 将归零。

标签: ios swift uitableview


【解决方案1】:

使用下面的代码此代码供您使用。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return arrData.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AddEventCell", for: indexPath) as! AddEventCell
        cell.txtName.tag = indexPath.row
        cell.txtName.delegate = self
        // Configure the cell...

        return cell
    }

    public func textFieldShouldReturn(_ textField: UITextField) -> Bool
    {
        if textField.tag < arrData.count - 1  {
            textField.resignFirstResponder()
            tbl.viewWithTag(textField.tag+1)?.becomeFirstResponder()
        }
        else
        {
            textField.resignFirstResponder()
        }
        return true
    }

【讨论】:

  • 这如何解决 OP 问题? textfieldShouldReturn 中的 tbl 是什么?它如何引用一个不可见的单元格?
【解决方案2】:

让我们做一个技巧。

1) 保存您的下一个文本字段索引作为第一响应者。

var respondTextFieldIndex: Int = 0

func makeTextFieldFirstResponder(textField:UITextField) -> Bool {
     let row = textField.tag 
     let indxPath = IndexPath(row: textField.tag + 1, section: 0)

     respondTextFieldIndex= textField.tag + 1

     if let cell = tblEditViewDetail.cellForRow(at: indxPath) as? InputCell {
    cell.txtField.firstResponder()
}

2) 在cellForRow 函数中,如果你的下一个单元格的索引等于respondTextFieldIndexlet 设置它firstResponder

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = *Your work here*.

    if indexPath.row == respondTextFieldIndex {
       cell.txtField.firstResponder()
    }
}

【讨论】:

  • 这将在单元格出列时将文本字段设置为第一响应者。据我了解,OP 希望这会自动发生。
【解决方案3】:

来自the docs for cellForRow :

表示表格单元格的对象,如果单元格不可见或 indexPath 超出范围,则为 nil。

所以如果单元格不可见,返回值应该是nil。您应该先使用scrollToRow,然后获取单元格并设置第一响应者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多