我创建了UIScrollView
的扩展名,当用户选择文本字段并出现键盘时,如果文本字段位于键盘中,则文本字段将向上滚动。我让它适用于UITextField
,但它似乎不适用于UITextView
。我在stackoverflow上搜索过很多帖子,但似乎无法找到任何帮助。以下是扩展程序的代码:
extension UIScrollView {
func respondToKeyboard() {
self.registerForKeyboardNotifications()
}
func registerForKeyboardNotifications() {
// Register to be notified if the keyboard is changing size i.e. shown or hidden
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(keyboardWasShown(_:)),
name: UIKeyboardWillShowNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(keyboardWillBeHidden(_:)),
name: UIKeyboardWillHideNotification,
object: nil
)
}
func keyboardWasShown(notification: NSNotification) {
if let info = notification.userInfo,
keyboardSize = info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.size {
self.contentInset.bottom = keyboardSize.height + 15
self.scrollIndicatorInsets.bottom = keyboardSize.height
var frame = self.frame
frame.size.height -= keyboardSize.height
}
}
func keyboardWillBeHidden(notification: NSNotification) {
self.contentInset.bottom = 0
self.scrollIndicatorInsets.bottom = 0
}
在我的视图控制器中,我只想设置它:
scrollView.respondToKeyboard()
有人能指出我如何将UITextView
作为一个扩展,以便在键盘挡住的情况下向上移动,这是正确的方向吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
对我来说这个解决方案适用于UITextView。也许你可以为Scrollview更新这个
// keyboard visible??
lazy var keyboardVisible = false
// Keyboard-Height
lazy var keyboardHeight: CGFloat = 0
func updateTextViewSizeForKeyboardHeight(keyboardHeight: CGFloat) {
textView.contentInset.bottom = keyboardHeight
self.keyboardHeight = keyboardHeight
}
func keyboardDidShow(notification: NSNotification) {
if let rectValue = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
if keyboardVisible == false {
let keyboardSize = rectValue.CGRectValue().size
keyboardVisible = true
updateTextViewSizeForKeyboardHeight(keyboardSize.height)
}
}
}
func keyboardDidHide(notification: NSNotification) {
if keyboardVisible {
keyboardVisible = false
updateTextViewSizeForKeyboardHeight(0)
}
}