显示键盘显示时将视图上移,用于stackview中的文本字段

时间:2018-09-07 10:55:20

标签: ios swift

我有一个场景,当键盘出现时我将视图向上移动,但是这种场景效果很好,但是一旦我开始键入视图,它就会回到其原始位置。需要注意的是,该文本字段位于堆栈视图中。

我的问题是,当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
}

2 个答案:

答案 0 :(得分:2)

将滚动视图添加为基本视图,然后在其中添加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
}

答案 1 :(得分:0)

我个人认为使用此library,否则您可以将整个UI管理到UITableview中,因此无需在该控制器中管理keyboardWillShow和keyboardWillHide方法。