我有一个用键盘移动屏幕底部的UIButton的功能。问题是,当用户按下一个键(开始在文本字段中写入)时,按钮会返回。
我尝试设置addBtn.translatesAutoresizingMaskIntoConstraints = true
仅当我的Xcode将main.storyboard设置为模拟器时才有效,否则会破坏约束。起初我认为这只是一个Xcode 9错误,但后来我在iTunes Connect上传了一个包,并要求我的女朋友通过TestFlight下载应用程序,实际上在设置translatesAutoresizingMaskIntoConstraints = true
func bindToKeyboard () {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
}
@objc func keyboardWillChange(_ notification : NSNotification) {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let startingFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endingFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endingFrame.origin.y - startingFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {self.frame.origin.y += deltaY
},completion: nil)
}
答案 0 :(得分:0)
好的,所以经过3个小时与这个bug的斗争后,我禁用了autoresizingmasks,并为底部约束创建了 outlet 。
在每个动画之后,我使用 deltaY
更新了该约束所以我的代码现在看起来像这样
func bindToKeyboard () {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
}
@objc func keyboardWillChange(_ notification : NSNotification) {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let startingFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endingFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endingFrame.origin.y - startingFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {self.frame.origin.y += deltaY
},completion: nil)
btc.constant -= deltaY
}
周六晚上多么愉快!我喜欢编程!