gpt4 book ai didi

objective-c - UIKeyboardDidShowNotification 被调用了两次

转载 作者:行者123 更新时间:2023-11-28 08:59:19 25 4
gpt4 key购买 nike

在我的 UIViewController 中,底部有两个 UITextField。所以在键盘上出现我正在尝试移动到上面。下面是我处理键盘的代码

override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHidden:", name: UIKeyboardDidHideNotification, object: nil)
}

override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidHideNotification, object: nil)
}

// MARK: - Handling Notification
func keyboardShown(notification: NSNotification){
if let initialFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
let convertedFrame = self.view.convertRect(initialFrame, fromView: nil)

iY = viewLogin.frame.origin.y

var currentFrame = viewLogin.frame
currentFrame.origin.y = convertedFrame.origin.y - 140
self.viewLogin.frame = currentFrame
UIView.animateWithDuration(0.2, animations: { () -> Void in

})
}
}


func keyboardHidden(notification: NSNotification){
var currentFrame = viewLogin.frame
currentFrame.origin.y = iY
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.viewLogin.frame = currentFrame
})
}

第一个 UITextField 工作正常。但是,当我尝试移动到第二个 UITextField 时,再次调用 keyboardShown() 并且我的 View 移回底部。我无法检测到实际原因。如果我遗漏了什么,请告诉我。

提前致谢

最佳答案

问题与自动布局有关。我按如下方式解决了

//    MARK: - Handling Notification
func keyboardShown(notification: NSNotification){
self.bottomConstraint.constant += 125
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.viewLogin.layoutIfNeeded()
})
}


func keyboardHidden(notification: NSNotification){
self.bottomConstraint.constant -= 125
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.viewLogin.layoutIfNeeded()
})
}

如果我们使用了 AutoLayout,我们需要更改约束的属性。

关于objective-c - UIKeyboardDidShowNotification 被调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32309371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com