개발/ios (swift)
scroll up textfield when keyboard show
즐거운 개발 인생
2022. 8. 8. 14:51
728x90
반응형
UITextField를 담고 있는 UIScrollView를 만든다.
scrollview contain textfield.
textField의 키보드가 나타날때 textfield가 가려지지 않도록 textfield를 스크롤 되게한다.
when textfield's keyboard show up, scroll up to textfield for textfield not covered.
class MainViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textFeid: UITextField!
overrid func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
@objc private func keyboardWillShow(_ notification: Notification)
{
print("keyboardWillShow")
guard let userInfo = notification.userInfo,
let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
return
}
scrollView.contentInset.bottom = keyboardFrame.size.height
scrollView.scrollRectToVisible(textField.frame, animated: true)
}
@objc private func keyboardWillHide(_ notification: Notification)
{
print("keyboardWillHide")
let contentInset = UIEdgeInsets.zero
scrollView.contentInset = contentInset
scrollView.scrollIndicatorInsets = contentInset
}
}
728x90
반응형