UIView.animateWithDuration无效

时间:2015-01-06 22:52:57

标签: ios swift

我正在制作一个消息应用程序。当键盘显示时,我希望UITextField随之向上移动,就像在Messages应用程序中一样。但是,我的动画调用无效。它不会像应该的那样为textInputView设置动画,但仍会在以下情况后调用完成块:

func keyboardWasShown(aNotification: NSNotification)
{
    var info = aNotification.userInfo! as Dictionary<NSObject,AnyObject>
    var kbSize = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size

    UIView.animateWithDuration(0.2, animations: { () -> Void in

        self.textInputView.frame.origin.y = self.view.frame.height - self.textInputView.frame.height - kbSize!.height


        println("Should move textInputView to: \(self.textInputView.frame.origin.y)") 

        }) { (bool) -> Void in


            println("Location of textInputView.frame.origin.y after animation: \(self.textInputView.frame.origin.y)")

    }
}

当我运行此代码时,它会打印:

应将textInputView.frame.origin.y移至:297.0

动画后的textInputView.frame.origin.y的位置:521.0

为什么不动画?

2 个答案:

答案 0 :(得分:1)

你的问题写得非常糟糕(并且不清楚你在问什么),但我注意到一个非常常见的错误。您试图设置框架的个别属性,而不是更改整个框架。

您的方法应如下所示:

func keyboardWasShown(notification: NSNotification) {

    let userInfo = notification.userInfo!
    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size.height

    UIView.animateWithDuration(0.2, animations: {

        var frame: CGRect = textInputView.frame
        frame.origin.y = CGRectGetMaxY(view.frame) - CGRectGetMaxY(textInputView.frame) - keyboardHeight

        textInputView.frame = frame // change the whole frame

    }, completion: nil)

}

请参阅一些UIKit 101教程以获得更多解释。

答案 1 :(得分:0)

问题在于关闭。如果你注意到你的关闭:

{ (bool) -> Void in


        println("Location of textInputView.frame.origin.y after animation: \(self.textInputView.frame.origin.y)")

}

在外面:

UIView.animateWithDuration(0.2, animations: { () -> Void in

    self.textInputView.frame.origin.y = self.view.frame.height - self.textInputView.frame.height - kbSize!.height


    println("Should move textInputView to: \(self.textInputView.frame.origin.y)") 

    })

就封锁而言,Apple Xcode 6.1的Intellisense很差。尝试手动编写闭包,而不是单击或按智能感知建议输入。