设置UIScrollView contentInset以在键盘出现时移动视图

时间:2017-09-10 02:00:38

标签: ios swift xcode uiscrollview xcode9-beta

你好! 我正在使用Swift 4和Xcode 9 Beta 6,当键盘出现时我尝试滚动滚动视图。我在Swift 3的另一个项目中做到了这一点。但是在这个项目中它不起作用。顺便说一句:在这个项目中,我不使用Storyboard。 这是我之前项目中使用的代码:

@objc func adjustForKeyboard(notification: Notification) {
    let userInfo = notification.userInfo!

    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)

    if notification.name == Notification.Name.UIKeyboardWillHide {
        feedbackScrollView.contentInset = UIEdgeInsets.zero
    } else {
        feedbackScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
    }
    feedbackScrollView.scrollIndicatorInsets = feedbackScrollView.contentInset
}

override func viewDidLoad() {
    super.viewDidLoad()
    setup()
    NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: Notification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
}

我希望有人可以帮助我。 谢谢!

0 个答案:

没有答案