【发布时间】:2018-07-19 20:18:36
【问题描述】:
我是 iOS 开发新手。我正在使用具有多个 TextField 和 TextView 的视图。我正在尝试向上移动视图以避免键盘隐藏编辑 TextField、TextView 内容。下面的代码适用于所有 TextField,但是当 TextView 是时它不会向上移动视图已编辑。希望您能理解我的问题。 提前致谢。
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
var keybordenabled = false
@objc func keyboardWillShow(notification: NSNotification) {
if(keybordenabled == false){
adjustInsetForKeyboardShow(show: true, notification: notification)
keybordenabled = true
}
}
@objc func keyboardWillHide(notification: NSNotification) {
keybordenabled = false
adjustInsetForKeyboardShow(show: false, notification: notification)
}
func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let adjustment = (keyboardFrame.height * (show ? 1 : -1)) + 20
scrollView.contentInset.bottom += adjustment
scrollView.scrollIndicatorInsets.bottom += adjustment
self.view.layoutIfNeeded()
}
func textViewDidBeginEditing(_ textView: UITextView)
{
if (textView.text == "Enter comment here...")
{
textView.text = ""
textView.textColor = .black
}
textView.becomeFirstResponder()
}
func textViewDidEndEditing(_ textView: UITextView)
{
if (textView.text == "")
{
textView.text = "Enter comment here..."
textView.textColor = .lightGray
}
textView.resignFirstResponder()
}
【问题讨论】:
-
使用 IQKeyboard 库
-
UITextViewTextDidBeginEditing UITextViewTextDidEndEditing
-
@ElTomato 对不起,我没明白你说的内容
标签: ios swift uiscrollview keyboard uikeyboard