Switching between Text fields on pressing return key in Swift

前端 未结 15 1434
名媛妹妹
名媛妹妹 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 10:00

    This approach needs some changes in table views and collection views, but it's okay for simple forms I guess.

    Connect your textFields to one IBOutletCollection, sort it by its y coordinate and in textFieldShouldReturn(_:) just jump to the next textfield until you reach the end:

    @IBOutlet var textFields: [UITextField]!
    
    ...
    
    textFields.sortInPlace { $0.frame.origin.y < $1.frame.origin.y }
    
    ...
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        if let currentIndex = textFields.indexOf(textField) where currentIndex < textFields.count-1 {
            textFields[currentIndex+1].becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }
        return true
    }    
    

    Or just look at sample project (xcode 7 beta 4)

    0 讨论(0)
  • 2020-12-04 10:01

    Swift 4.2

    This is a More Generic and Easiest Solution, you can use this code with any amount of TextFields. Just inherit UITextFieldDelegate and update the Textfield Tag according to the order and copy this function

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let txtTag:Int = textField.tag
    
        if let textFieldNxt = self.view.viewWithTag(txtTag+1) as? UITextField {
            textFieldNxt.becomeFirstResponder()
        }else{
            textField.resignFirstResponder()
        }
    
        return true
    }
    
    0 讨论(0)
  • 2020-12-04 10:02

    You can go with field tags. I think that's easier than other.

    First of all you have enter code hereto give tag to your field.

    On my code usernameField tag is 0 and passwordField tag is 1. And I check my tag. Then doing proccess.

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 0 {
            passwordField.becomeFirstResponder()
        } else if textField.tag == 1 {
            self.view.endEditing(true)
            loginFunc()
        } else {
            print("Hata var")
    
        }
         return false
    }
    

    If click return on username field, go password. Or If you click return when password field, run login function to login.

    0 讨论(0)
提交回复
热议问题