////
Search
⌨️

Keyboard Control

본 글에서는 UITextField 사용시 Keyboard 제어 방법에 대해 다룹니다.

1. UIViewController - UITextFieldDelegate Protocol 채택

기본 Code
import UIKit class ViewController: UIViewController, UITextFieldDelegate { //MARK: - Property //MARK: - IBoutlet @IBOutlet weak var textField: UITextField! //MARK: - Method //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self } }
Swift
복사
Extension Code
import UIKit class ViewController: UIViewController { //MARK: - Property //MARK: - IBoutlet @IBOutlet weak var textField: UITextField! //MARK: - Method //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self } } extension ViewController: UITextFieldDelegate { }
Swift
복사

2. 화면 터치 시 키보드 내리기

/// 화면 터치 시 키보드 내리기 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) }
Swift
복사

3. return 버튼 클릭 시 키보드 내리기

/// return 클릭 시 키보드 내리기 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true }
Swift
복사

4. 전체 코드

기본 Code
import UIKit class ViewController: UIViewController, UITextFieldDelegate { //MARK: - Property //MARK: - IBoutlet @IBOutlet weak var textField: UITextField! //MARK: - Method //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self } /// 화면 터치 시 키보드 내리기 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } /// return 클릭 시 키보드 내리기 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
Swift
복사
Extension Code
import UIKit class ViewController: UIViewController { //MARK: - Property //MARK: - IBoutlet @IBOutlet weak var textField: UITextField! //MARK: - Method //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self } } //MARK: - Extension extension ViewController: UITextFieldDelegate { /// 화면 터치 시 키보드 내리기 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } /// return 클릭 시 키보드 내리기 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
Swift
복사

5. 실행 결과