我不知道为什么动画在UIKeyboardDidShowNotification事件中正常工作但在UIKeyboardWillShowNotification事件中不起作用。
代码如下所示:
评论代码中的动画效果不好,颜色会改变,但持续时间= 4不正确
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardDidShow:"), name:UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardDidHide:"), name:UIKeyboardDidHideNotification, object: nil)
}
deinit {NSNotificationCenter.defaultCenter().removeObserver(self)}
func keyboardDidShow(notification: NSNotification) {
showAnima1()
}
func keyboardDidHide(notification: NSNotification) {
showAnima2()
}
func keyboardWillShow(notification: NSNotification) {
// showAnima1() // animate not work here
}
func keyboardWillHide(notification: NSNotification) {
// showAnima2() // animate not work here
}
func showAnima1() {
UIView.animateWithDuration(4, delay: 0, options: UIViewAnimationOptions(rawValue: 7), animations: { () -> Void in
self.view.backgroundColor = UIColor.greenColor()
}) { (finish) -> Void in
print("animate state = \(finish)")
}
}
func showAnima2() {
UIView.animateWithDuration(4, delay: 0, options: UIViewAnimationOptions(rawValue: 7), animations: { () -> Void in
self.view.backgroundColor = UIColor.whiteColor()
}) { (finish) -> Void in
print("animate state = \(finish)")
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {self.view.endEditing(false)}
}
抱歉,我看到源代码中的评论说:
// Each notification includes a nil object and a userInfo dictionary containing the
// begining and ending keyboard frame in screen coordinates. Use the various UIView and
// UIWindow convertRect facilities to get the frame in the desired coordinate system.
// Animation key/value pairs are only available for the "will" family of notification.
最后一条评论可能意味着“做”了一系列通知???
答案 0 :(得分:0)
我有同样的问题。
看起来必须从主线程调用animate函数。将动画包装在DispatchQueue.main.async
中对我有用:
@objc func keyboardWillHide(notification: NSNotification) {
DispatchQueue.main.async {
UIView.animate(withDuration: 2.0) {
self.view.frame.origin.y = 0
}
}
}