Avoid keyboard closing when iPhone rotated XCode Swift

青春壹個敷衍的年華 提交于 2019-12-24 12:34:23

问题


I have in left navigation item UITextField. When I type something in there and rotate device, keyboard hides everytime.

I tried to handle UIKeyboardWillHideNotification, but all what I got is: keyboard closes and shows again after that. It's not good, I need to rotate keyboard along with view...

Please help in Swift 2.


回答1:


Okay, I found the solution! First, need to implement delegate:

ViewController: UIViewController, UITextFieldDelegate

Next, add to viewDidLoad method:

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
}

To the end, realise textFieldShouldEndEditing function:

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
    //here we can add some if-block for orientation change or smth else
    return false
}



回答2:


override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    textField.becomeFirstResponder()
}

The method above here gets called when the device will rotate, as you don't care about the orientation we don't check it and simple instruct the textfield you are editing to become first responder.



来源:https://stackoverflow.com/questions/33965218/avoid-keyboard-closing-when-iphone-rotated-xcode-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!