如何从上到下为UIView制作动画,反之亦然?

时间:2017-09-04 09:21:01

标签: ios swift animation uiimageview

我正在尝试从上到下动画UIImageView,反之亦然。 我尝试了代码:

以前的值为(y == 0):

laserImageView.frame = CGRect(x: 0, y: 0.0, width: 300.0, height: 300.0)

并希望将其设置为500.0

UIView.animate(withDuration: 3.0, delay: 0.2, options: [.curveEaseInOut], animations: {
    laserImageView.frame = CGRect(x: 0, y: 500.0, width: 300.0, height: 300.0)
}) { (finished) in
    if finished {
        // Repeat animation from bottom to top
    }
}

但是当我运行我的应用程序时,UIImageView出现在最后一点(y == 500)而没有任何动画,例如初始位置为500.0但不是0.0

我不明白为什么动画不起作用。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

试试这段代码:

class ViewController: UIViewController {

let laserImageView = UIImageView(frame: CGRect(x: 0, y: 0.0, width: 300.0, height: 300.0))



override func viewDidLoad() {
    super.viewDidLoad()

    laserImageView.backgroundColor = UIColor.blue
    self.view.addSubview(laserImageView)
}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    bottom()


}

func bottom()  {

    UIView.animate(withDuration: 3.0, delay: 0.2, options: [.curveEaseInOut], animations: {
        self.laserImageView.frame = CGRect(x: 0, y: 500.0, width: 300.0, height: 300.0)
    }) { (finished) in
        if finished {
            // Repeat animation from bottom to top
            self.Up()
        }
    }
}

func Up()  {

    UIView.animate(withDuration: 3.0, delay: 0.2, options: [.curveEaseInOut], animations: {
        self.laserImageView.frame = CGRect(x: 0, y: self.laserImageView.bounds.origin.y, width: 300.0, height: 300.0)
    }) { (finished) in
        if finished {
            // Repeat animation to bottom to top
            self.bottom()
        }
    }

}

}

答案 1 :(得分:-2)

这样做的一种方法是使用以下方法获取要为其设置动画的顶级约束的IBOutlet并更新约束的值: -

- (IBAction)animateButton:(UIButton *)sender {
    [UIView transitionWithView:_topView duration:0.8 options:UIViewAnimationOptionRepeat animations:^{
        _headerViewTopConstraint.constant = self.view.frame.size.height - 20;
         [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
    }];
}

enter image description here

答案 2 :(得分:-3)

对于那些想要使用代码的人,尽管界面构建者可以使用以下答案: -

__weak FirstViewController *weakSelf = self;
[UIView transitionWithView:_topView duration:0.4 options:UIViewAnimationOptionCurveEaseIn animations:^{
    //
    _topView.frame = CGRectMake(0, 300, _topView.frame.size.width, _topView.frame.size.height);
    [weakSelf.view layoutIfNeeded];
} completion:^(BOOL finished) {
    //
}];

请尝试发布完整的问题,尽管低估了答案:)谢谢

相关问题