使用滚动视图管理键盘

时间:2017-04-18 02:00:08

标签: ios swift3 uiscrollview

我目前正在学习关于来自raywenderlich的滚动视图的课程。有关如何将观察者添加到通知中心以跟踪keyBoard显示时间的课程。以下是代码的外观。

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)


func keyboardWillHide(notification: Notification) {
    adjustKeyboardInset(false, notification: notification)
}

func keyboardWillShow(notification: Notification) {
    adjustKeyboardInset(true, notification: notification)
}

func adjustKeyboard(isShown: Bool, notification: Notification) {
    let userInfo = notification.userInfo ?? [:]
    let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue

    let adjustedHeight = keyboardFrame.height * (isShown ? 1 : -1) + 20

    mySV.contentInset.bottom += adjustedHeight
    mySV.scrollIndicatorInsets.bottom += adjustedHeight
}

这是第一次单击文本字段时正常工作。但是,当您继续单击textField时,它会不断为其添加空间。

非常感谢任何帮助。 :)

1 个答案:

答案 0 :(得分:0)

最好不要使用“+ =”操作。替代解决方案可能是:

var originalBottom:CGFloat = 0.0
var originalIndicatorBottom:CGFloat = 0.0

override func viewDidLoad() {
    super.viewDidLoad()
    originalBottom = mySV.contentInset.bottom.constant
    originalIndicatorBottom:CGFloat = mySV.scrollIndicatorInsets.bottom.constant
}

//......    

func adjustKeyboard(isShown: Bool, notification: Notification) {
    let userInfo = notification.userInfo ?? [:]
    let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue

    let adjustedHeight = keyboardFrame.height + 20

    if isShown {
        mySV.contentInset.bottom = originalBottom + adjustedHeight
        mySV.scrollIndicatorInsets.bottom = originalIndicatorBottom + adjustedHeight
    }
    else
    {
       mySV.contentInset.bottom = originalBottom 
       mySV.scrollIndicatorInsets.bottom = originalIndicatorBottom 
    }

}