[swift] IQKeyboardManager가 제공하는 커스텀 키보드 도구 모음의 활용 예시를 보여주세요.

이번에는 IQKeyboardManager 라이브러리를 사용하여 iOS 앱에 커스텀 키보드 도구 모음을 구현하는 방법에 대해 살펴보겠습니다.

  1. IQKeyboardManager 라이브러리 설치
    • CocoaPods를 사용하여 IQKeyboardManager를 설치합니다. Podfile에 다음 라인을 추가한 후 pod install 명령을 실행합니다.

      pod 'IQKeyboardManagerSwift'
      
  2. IQKeyboardManager 활성화
    • AppDelegate.swift 파일에서 application(_:didFinishLaunchingWithOptions:) 메서드에 다음 코드를 추가하여 IQKeyboardManager를 활성화합니다.

      import IQKeyboardManagerSwift
      
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          IQKeyboardManager.shared.enable = true
          return true
      }
      
  3. 커스텀 키보드 도구 모음 구현
    • UITextField나 UITextView의 inputAccessoryView 속성을 사용하여 커스텀 키보드 도구 모음을 추가할 수 있습니다. 다음은 숫자 키보드와 닫기 버튼을 포함한 예시입니다.

      import UIKit
      
      class CustomKeyboardAccessoryView: UIView {
          var textField: UITextField?
      
          override init(frame: CGRect) {
              super.init(frame: frame)
              setupUI()
          }
      
          required init?(coder: NSCoder) {
              super.init(coder: coder)
              setupUI()
          }
      
          private func setupUI() {
              let numberButton = UIButton(type: .custom)
              numberButton.setTitle("123", for: .normal)
              numberButton.setTitleColor(.blue, for: .normal)
              numberButton.addTarget(self, action: #selector(numberButtonTapped), for: .touchUpInside)
              addSubview(numberButton)
      
              let closeButton = UIButton(type: .custom)
              closeButton.setTitle("Close", for: .normal)
              closeButton.setTitleColor(.red, for: .normal)
              closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
              addSubview(closeButton)
      
              // Layout code
          }
      
          @objc private func numberButtonTapped() {
              textField?.inputView = UIView() // 커스텀 숫자 키보드로 변경
              textField?.reloadInputViews()
          }
      
          @objc private func closeButtonTapped() {
              textField?.resignFirstResponder()
          }
      }
      
      // textField가 포함된 ViewController에서 사용 예시
      class ViewController: UIViewController {
          @IBOutlet weak var textField: UITextField!
      
          override func viewDidLoad() {
              super.viewDidLoad()
              textField.inputAccessoryView = CustomKeyboardAccessoryView()
              (textField.inputAccessoryView as? CustomKeyboardAccessoryView)?.textField = textField
          }
      }
      
  4. 실행
    • 앱을 실행하고 UITextField를 탭하여 활성화한 후에 키보드가 나타나면, 추가된 커스텀 키보드 도구 모음을 확인할 수 있습니다.

IQKeyboardManager 라이브러리를 사용하면 편리하게 커스텀 키보드 도구 모음을 구현할 수 있습니다. 사용자 경험을 향상시키고 키보드 관련 이슈를 처리하는 데 도움이 될 것입니다.

참고 자료: