Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift next button change textfield

I have an app built with Swift and iOS8. In my ViewController I had two textfields.

I use this code:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    if textField == self.textfield_A {
        self.textfield_B.becomeFirstResponder()
    }
    if textField == self.textfield_B {
        self.textfield_B.resignFirstResponder()
    }
    return true
}

The effect:

I select textfield_A and Press the Next Button -> the cursor jump to textfield_B

On textfield_B I press the Done Button -> the keyboard will be hidden.

All works fine.

But now I have made a change and the code doesn't work like this anymore.

I changed the textfield_A to a textView.

Any idea how I have to modify my code?

like image 734
Ghost108 Avatar asked Dec 05 '22 02:12

Ghost108


1 Answers

You have to add an extension, this is the extension for swift 3.0

extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
    guard let last = fields.last else {
        return
    }
    for i in 0 ..< fields.count - 1 {
        fields[i].returnKeyType = .next
        fields[i].addTarget(fields[i+1], action: #selector(UIResponder.becomeFirstResponder), for: .editingDidEndOnExit)
    }
    last.returnKeyType = .done
    last.addTarget(last, action: #selector(UIResponder.resignFirstResponder), for: .editingDidEndOnExit)
    }
} 

and after you add this line of code:

UITextField.connectFields(fields: [field1, field2, field3])
like image 82
edoriggio Avatar answered Dec 22 '22 08:12

edoriggio