Switching between Text fields on pressing return key in Swift

前端 未结 15 1439
名媛妹妹
名媛妹妹 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)

提交回复
热议问题