我有一个场景,当键盘出现时我将 View 向上移动,这个场景工作正常,但是一旦我开始键入, View 就会回到原来的位置。需要注意的是,文本字段位于堆栈 View 中。
我的问题是,有没有一种方法可以阻止 View 在文本编辑开始时返回到其原始位置。
这是我的代码:
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
}
最佳答案
添加一个 ScrollView 作为你的基础 View ,然后在里面添加你的内容 View
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
}
关于ios - 显示键盘时向上移动 View ,用于堆栈 View 中的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221059/