Blog

How to prevent Swift UITextField from being hidden by keyboard

When typing TextFeild in Swift, it is common for the keyboard coming out of the screen to be invisible.
I searched and found that all of them were implemented by myself.
But I found a useful library.

What you want to Implement

f:id:happy_teeth_ago:20200123130556g:plain

Use library TPKeyboardAvoiding

Official site here

Write in pod file and execute pod install

pod 'TPKeyboardAvoiding'
$ pod install

Analyzing dependencies
Downloading dependencies
Installing TPKeyboardAvoiding (1.3.3)
Generating Pods project
Integrating client project

Note! After installing the pod, be sure to restart Xcode and launch it from the xcworkspace icon

View settings in StoryBoard

Place scroll view
Place a view under that
The structure is like this.

Keyboard…is ScrollView
SecondView is View
Constraints from default View to ScrollView are
Set top, bottom, left and right to 0

Constraints from ScrollView to View are
Set Align Center X, Y

Set TPKeyboardAvoidingScrollView class to ScrollView

Important! Connect delegate of textField to controller

Code description

Basically, this library picks up the input start event of TextField,
Only the processing when the return key is pressed is described.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var yourNameTF: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
    }
  
}

extension ViewController: UITextFieldDelegate{
//Close text field with return key
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

 

This library is recommended because it can be easily implemented.
Also, if you apply the class, you can use it on any screen and reduce the amount of code.


<< Previous Blog MrSurveyor2-SIM data include
Next Blog>> Reasons why Japan is weaker in the IT field than Europe and the United States-1