Swift中的ScrollView和键盘 [英] ScrollView and keyboard in Swift
本文介绍了Swift中的ScrollView和键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始创建一个简单的iOS应用,该应用可以执行一些操作.
I started creating a simple iOS app that does some operations.
但是当键盘出现时,我遇到了一些问题,隐藏了我的一个文本字段.
But I'm having some problems when the keyboard appears, hiding one of my textfields.
我认为这是一个普遍的问题,我做了一些研究,但找不到能解决我问题的任何东西.
I think it's a common problem and I did some research but I couldn't find anything that solved my problem.
我想使用ScrollView而不是为文本字段设置动画以使其可见.
I want to use a ScrollView rather than animate the textfield to make it visible.
推荐答案
在ViewDidLoad中,注册通知:
In ViewDidLoad, register the notifications:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil)
在下面添加观察者方法,这些方法将在出现键盘时自动滚动.
Add below observer methods which does the automatic scrolling when keyboard appears.
@objc func keyboardWillShow(notification:NSNotification) {
guard let userInfo = notification.userInfo else { return }
var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height + 20
scrollView.contentInset = contentInset
}
@objc func keyboardWillHide(notification:NSNotification) {
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInset
}
这篇关于Swift中的ScrollView和键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文