ios - 动画框架偶尔有效

标签 ios swift uiview animatewithduration

这是我的动画 View 的函数

func animateViewMoving (up:Bool, moveValue :CGFloat) {

    let movementDuration:NSTimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)
    self.view.setNeedsLayout()
    UIView.animateWithDuration(movementDuration, animations: {
    self.view.layoutIfNeeded()
    self.view.frame.origin.y += movement
    })

}

我在 UITextFieldDelegate 的这两个函数上调用了这个函数

func textFieldDidBeginEditing(textField: UITextField) {

        animateViewMoving(true, moveValue: 200)

}

func textFieldDidEndEditing(textField: UITextField) {

        animateViewMoving(false, moveValue: 200)

}

问题是这样的——每当我第一次运行构建并打开 View 时, View 会在按下 textField 时向上移动,在编辑 textField 结束时向下移动。但是,如果我返回到上一个 View 并再次进入 View ,则 View 不会在按下 textField 时向上移动。为什么 animateWithDuration 工作不规律?

最佳答案

抱歉,我不懂 swift,所以我只用 objective-C 编写我的解决方案。

我假设您正在使用 AutoLayout。如果是这种情况,我建议在为 View 设置动画时,为它的约束设置动画,而不是为 View 的框架设置动画。之前在给view的frame做动画的时候遇到了很多问题。

这是一个示例:

- (void)moveSubview
{
    _subviewLeadingSuperLeading.constant = 20; //just a sample to move the subview horizontally.

    [UIView animateWithDuration:0.5 animations:^
     {
         [self.view layoutIfNeeded];
     }

     completion:^(BOOL isFinished)
     {
         //Do whatever you want
     }];
}

希望对您有所帮助。 :)

关于ios - 动画框架偶尔有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36697729/

相关文章:

ios - 每当使用 CocoaPods 重建工作区文件时,防止 XCode 折叠我的文件夹

ios - 应用程序委托(delegate)的 Swift Xcode 7 错误

uitableview - 动态地将自定义对象数组排序到部分 UITableview

ios - touchesBegin() 创建的 UIView 不会被删除,因为当用户从 iPad 上移开手指时,touchesEnded() 永远不会被调用

ios - 试图遍历 UIView 和所有 subview 以获得第一响应者,但无法正常工作

ios - 在导航栏中嵌入 CGRect

iphone - 在 iOS 7 上读取 iPhone 的通话记录

swift - 通过在 Swift 中将元素映射到结构来填充缓冲区

swift - 用 SKScene 和 SKActions 替换 CALayer 和 CABasicAnimation

ios - 如何使父 View 自动调整大小并与其 subview 协调?