Switching between Text fields on pressing return key in Swift

前端 未结 15 1519
名媛妹妹
名媛妹妹 2020-12-04 09:25

I\'m designing an iOS app and I want that when the return key is pressed in my iPhone it directs me to the next following text field.

I have found a couple of similar

15条回答
  •  广开言路
    2020-12-04 09:58

    An alternative method for purists who don't like using tags, and wants the UITextField delegate to be the cell to keep the components separated or uni-directional...

    1. Create a new protocol to link the Cell's and the TableViewController.

      protocol CellResponder {
        func setNextResponder(_ fromCell: UITableViewCell)
      }
      
    2. Add the protocol to your cell, where your TextField Delegate is also the cell (I do this in the Storyboard).

      class MyTableViewCell: UITableViewCell, UITextFieldDelegate {
        var responder: CellResponder?
      
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
          responder?.setNextResponder(self)
          return true
        }
      }
      
    3. Make your TableViewController conform to the CellResponder protocol (i.e. class MyTableViewController: UITableViewController, CellResponder) and implement the method as you wish. I.e. if you have different cell types then you could do this, likewise you could pass in the IndexPath, use a tag, etc.. Don't forget to set cell.responder = self in cellForRow..

      func setNextResponder(_ fromCell: UITableViewCell) {
        if fromCell is MyTableViewCell, let nextCell = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as? MySecondTableViewCell {
      
          nextCell.aTextField?.becomeFirstResponder()
      
        } ....
      }
      

提交回复
热议问题