반응형
UITextField, UITextView 입력 시 키보드가 활성화될 때 키보드에 가려지지 않도록 하는 방법을 알아보도록 한다.
아래 샘플은 UITableView에서 입력 시 키보드에 가려지지 않도록 처리하는 예제이다.
class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
private var activeTextField: UITextField?
private var activeTextView: UITextView?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
registerForKeyboardNotifications()
}
... 중간 생략 ...
// 활성화된 TextView 입력 필드를 추적 및 갱신
func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextField = textField
activeTextView = nil
}
func textFieldDidEndEditing(_ textField: UITextField) {
activeTextField = nil
}
// 활성화된 TextView 입력 필드를 추적 및 갱신
func textViewDidBeginEditing(_ textView: UITextView) {
activeTextView = textView
activeTextField = nil
}
func textViewDidEndEditing(_ textView: UITextView) {
activeTextView = nil
}
}
extension ViewController {
// 키보드가 나타날 때, 키보드가 내려갈 때 이벤트 등록
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
// 키보드가 나타날 때 실행되며, 현재 활성화된 입력 필드가 키보드에 의해 가려지지 않도록 스크롤
@objc func keyboardWasShown(_ notification: NSNotification) {
guard let userInfo = notification.userInfo,
let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
var aRect = self.view.frame
aRect.size.height -= keyboardHeight
if let activeTextField = activeTextField, let textFieldRect = activeTextField.superview?.convert(activeTextField.frame, to: tableView) {
if !aRect.contains(textFieldRect.origin) {
tableView.scrollRectToVisible(textFieldRect, animated: true)
}
} else if let activeTextView = activeTextView, let textViewRect = activeTextView.superview?.convert(activeTextView.frame, to: tableView) {
if !aRect.contains(textViewRect.origin) {
tableView.scrollRectToVisible(textViewRect, animated: true)
}
}
}
// 키보드가 내려갈 때
@objc func keyboardWillBeHidden(_ notification: NSNotification) {
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
}
}
반응형
'개발 > iOS' 카테고리의 다른 글
iOS 18 주요 추가 및 변경 사항 (0) | 2024.10.06 |
---|---|
[App Store Connect] 'NDEF is disallowed'. 에러 해결방법 (0) | 2024.10.04 |
UITextField 숫자 입력 시 콤마 추가 및 사용 (0) | 2024.05.14 |
Floating, Dragging Button (1) | 2024.01.04 |
XOR 연산을 이용한 문자열 비교 (0) | 2023.12.07 |