[Swift in Xcode]Fixing UITextField keyboard problem

2016-01-25

When coding in swift, for the UITextField, it is easy to find some problem comes with the annoying presenting way for keyboard. This is article, I will focus on two main problems.

  • How to hide a keyboard, when I do not need that
  • How to let the keyboard do not cover my useful information(textfield, button, etc..)

Give some explanation for the first problem, let’s take a signin page as an example, after we typed our username and password, we need to click the submit button. However, in most case, the keyboard covers the button, and we need to click “return”(iphone users usually use that button on the keyboard) to hide the keyboard.
Give some explanation for the second problem, if on a page, we have so many textFields to fill in, then we will come with another problem that, when we click the textField, the keyboard will cover the textField, and often, we can not see what we typed. So to solve this problem, we need to move all the view up.

How to hide a keyboard, when I do not need that

The most easiest way to do this is add a resignFirstResponder() to the textField. The following steps are:

  1. Control drag the UITextField to the destination view controller

  2. The connection should be “Action”

  3. Change the “Event” to “Did End On Exit”

  4. Put these code inside the function usernameTF.resignFirstResponder()

Here is an example.:-)

1
2
3
@IBAction func endEmail(sender: UITextField) {
emailTF.resignFirstResponder()
}

Then, you finished all the steps 🙂

How to let the keyboard do not cover my useful information(textfield, button, etc..)

The solution should be add a scrollView, and each time, we move the scrollView up, and that will not covered the useful information.

1
2
3
4
func textFieldDidBeginEditing(textField: UITextField) {
print("wow")
scrollView.setContentOffset(CGPointMake(0, 200), animated: true)
}

The above code shows that when the textFieldDidBeginEditing , we started move the scrollView, 200 should be changed to fit your own condition. And here is one more useful tips: you may not need to move the scrollView, every times, when you click the textField, so let’s pay attention to the argument, textField, you can write a if-statement to judge is the textField what you want or not. And then do the move action. 🙂

If you have any questions, please comment below, thank you for reading. 🙂


Comments: