我正试图在键盘出现时提高视图,但它只是反弹回来。如果我给Y CGRectOffset
一个正值(向下移动View),那么它就会停留。
@IBOutlet weak var PPI: MainTextFields!
var KbHeight: CGFloat!
//----------------------------------------------
func animateTextField(up: Bool) {
let TFMovement = (up ? -KbHeight : KbHeight)
UIView.animateWithDuration(0.7, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, TFMovement)
})
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
KbHeight = keyboardSize.height
self.animateTextField(true)
}
}
}
func keyboardWillHide(notification: NSNotification) {
self.animateTextField(false)
}
//----------------------------------------------
// Touch Outside Keypad to leave it
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)
// For TextField Movement
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// For TextField Movement
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
PPI.delegate = self
}
我对CGRectOffset
函数中的keyboardWillShow
做错了吗?我对Swift相对较新,并从教程中得到了这个,但似乎没有正常工作。
答案 0 :(得分:0)
当我的viewController加载时,我想要从左到右的背景移动动画。这是我在我的应用程序中所做的:
var backgroundImageView: UIImageView = UIImageView(image:
UIImage(named: "background.png")!)
self.view.addSubview(backgroundImageView)
self.view.sendSubviewToBack(backgroundImageView)
UIView.animateWithDuration(20.0, animations: {
backgroundImageView.frame = CGRect(x: -700, y: 0, width: backgroundImageView.image!.size.width, height:backgroundImageView.image!.size.height)
})
希望这个例子有所帮助:)
尝试使用CGRect,并给它正y值。这样,您将在动画结束时获得此矩形位置。当键盘关闭时,将其移回y值0。
答案 1 :(得分:0)
原来是因为自动布局约束我必须进行上边距,所以需要更改该约束的常量和行:
self.view.frame = CGRectOffset(self.view.frame, 0, TFMovement)
根本不需要。