Search code examples
iosswiftuitableviewuitextfield

How to goto next textfield when using one common textfield for all textfield?


I have placed one UITextField in storyboard within tableview, and create multiple textfield (4 nos.) using code.

my issue is I cannot goto 2nd uitextfield when press return key on keyboard. I have use below code, in tableview cell

func textFieldShouldReturn(textField: UITextField) -> Bool {
    let nextTag: NSInteger = textField.tag + 1

    let nextResponder: UIResponder = textField.superview!.viewWithTag(nextTag)!
    if (nextResponder != nil) {

        nextResponder.becomeFirstResponder()
    } else {
      
        textField.resignFirstResponder()
    }
    return false 
}

Solution

  • First set the textField tag with current row in cellForRowAtIndexPath methods.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
            
            cell.textField.tag = indexPath.row
    
        return cell
        }
    

    After that get the next cell in textFieldShouldReturn method and set the next cell textField firstResponder.

        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let nexttag = textField.tag + 1
        if nexttag < tableView.numberOfRows(inSection: 0) {
            let nextIndexPath = IndexPath(row: nexttag, section: 0)
            if let cell = tableView.cellForRow(at: nextIndexPath) as? MyCell{
                cell.textfield.becomeFirstResponder()
                tableView.scrollToRow(at: nextIndexPath, at: .none, animated: true)
            }
        } else {
            textField.resignFirstResponder()
        }
        return false
    }