UITextField에 텍스트를 입력할 때 사용하는 키보드를 올리고, 내려보자

 

방법은 간단하다

becomeFirstResponder 와 resignFirstResponder를 사용하면 된다.

 

버튼을 눌렀을 때 키보드를 올리고 내리는 함수를 작성해보자

override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(textField)
        view.addSubview(showButton)
        view.addSubview(hideButton)
        showButton.addTarget(self, action: #selector(didTapShowButton), for: .touchUpInside)
        hideButton.addTarget(self, action: #selector(didTapHideButton), for: .touchUpInside)
    }

    @objc private func didTapShowButton(){
        //TextField의 키보드를 올리자
        textField.becomeFirstResponder()
    }
    @objc private func didTapHideButton(){
        //TextField의 키보드를 내리자
        textField.resignFirstResponder()
    }

결과는 아래와 같다

 

 

 

전체코드

import UIKit
import Foundation


class ViewController: UIViewController{
    private let textField : UITextField = {
        let textField = UITextField()
        textField.placeholder = "문자열 입력"
        return textField
    }()
    
    private let showButton : UIButton = {
        let button = UIButton()
        button.setTitle("Show", for: .normal)
        button.backgroundColor = .blue
        return button
    }()
    private let hideButton : UIButton = {
        let button = UIButton()
        button.setTitle("Hide", for: .normal)
        button.backgroundColor = .red
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(textField)
        view.addSubview(showButton)
        view.addSubview(hideButton)
        showButton.addTarget(self, action: #selector(didTapShowButton), for: .touchUpInside)
        hideButton.addTarget(self, action: #selector(didTapHideButton), for: .touchUpInside)
    }

    @objc private func didTapShowButton(){
        //TextField의 키보드를 올리자
        textField.becomeFirstResponder()
    }
    @objc private func didTapHideButton(){
        //TextField의 키보드를 내리자
        textField.resignFirstResponder()
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        textField.frame = CGRect(x: 30, y: 300, width: view.frame.width-60, height: 50)
        showButton.frame = CGRect(x: 100, y: 400, width: 50, height: 30)
        hideButton.frame = CGRect(x: 250, y: 400, width: 50, height: 30)
    }
}
복사했습니다!