[英]Move view up when keyboard shows, for textfield in a stackview
我有一个场景,当键盘出现时我将视图向上移动,这种情况很好,但是,一旦我开始键入视图,它就会回到其原始位置。 需要注意的是,该文本字段位于堆栈视图中。
我的问题是,有什么方法可以阻止textEditing开始时视图返回到其原始位置。
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector:#selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
var isScroll = false
@objc func keyboardWillShow(sender: NSNotification) {
mainView.frame.origin.y = -100
}
@objc func keyboardWillHide(sender: NSNotification) {
mainView.frame.origin.y = 0
}
添加滚动视图作为基本视图,并在其中添加contentview然后
func keyboardShown(_ notification: Notification){
var userInfo = notification.userInfo!
let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
let contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize!.height + 40), 0.0)
self.mainScrollView.contentInset = contentInsets
self.mainScrollView.scrollIndicatorInsets = contentInsets
// **-- Scroll when keyboard shows up
let aRect = self.view.frame
self.mainScrollView.contentSize = aRect.size
/* if((self.activeTextField) != nil)
{
self.scrollView.scrollRectToVisible(self.activeTextField!.frame, animated: true)
}*/
}
func keyboardHidden(_ notification: Notification) {
let contentInsets = UIEdgeInsets.zero
self.mainScrollView.contentInset = contentInsets
self.mainScrollView.scrollIndicatorInsets = contentInsets
// **-- Scroll when keyboard shows up
self.mainScrollView.contentSize = self.containerView.frame.size
}
我个人认为使用此库,否则您可以将整个UI管理到UITableview中,因此无需在该控制器中管理keyboardWillShow和keyboardWillHide方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.