键盘显示时视图位置重置

时间:2016-06-06 14:34:23

标签: ios swift autolayout

逗人,

我有以下情况:

  • 我在屏幕“上方视图和下方视图”中有两个视图
  • 上方视图占据整个屏幕,下方的视图因为“它的Y轴从另一个视图高度的末端开始”而显示不可见
  • 当用户按下按钮时,我向上移动两个视图,使下方视图可见,上方视图隐藏。

一切都很好,问题出在此处:

下方视图中有一个文本框,当用户选择添加文本时,键盘会显示并简单地将所有视图重置为其初始位置,这会破坏所有内容“上部视图再次显示。

以下是我用来移动视图的代码:

@IBAction func signInWithEmailPressed(sender: AnyObject) {

    UIView.animateWithDuration(1, delay: 0, options: .CurveEaseInOut, animations: {
        self.topView.center.y -= self.topView.bounds.height
        self.bottomView.center.y -= self.topView.bounds.height
        }, completion: { finished in
            if(finished) {

                self.view.layoutIfNeeded()
            }
    })
}

不知道为什么它会一直重置所有视图。感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:-1)

试试这..............

override func viewDidLoad() {
 super.viewDidLoad() 

 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("makeSpaceForKeyboard:"), name:UIKeyboardWillShowNotification, object: nil);
 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("makeSpaceForKeyboard:"), name:UIKeyboardWillHideNotification, object: nil);
}

deinit{
 NSNotificationCenter.defaultCenter().removeObserver(self)
}



func makeSpaceForKeyboard(notification: NSNotification) {

    let info = notification.userInfo!
    let keyboardHeight:CGFloat = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size.height
    let duration:Double = info[UIKeyboardAnimationDurationUserInfoKey] as! Double

    if notification.name == UIKeyboardWillShowNotification && keyboardIsVisible == false{

        keyboardIsVisible = true

        UIView.animateWithDuration(duration, animations: { () -> Void in
            var frame = self.view.frame
            frame.size.height = frame.size.height - keyboardHeight
            self.view.frame = frame
        })

    } else if keyboardIsVisible == true && notification.name == UIKeyboardWillShowNotification{

    }else {
        keyboardIsVisible = false

        UIView.animateWithDuration(duration, animations: { () -> Void in
            var frame = self.view.frame
            frame.size.height = frame.size.height + keyboardHeight
            self.view.frame = frame
        })
    }
}