最简单的代码,用于将UIImage视图从A点移动到B点

时间:2015-05-06 02:50:17

标签: ios swift animation uiimageview uiimage

@IBOutlet weak var imageView: UIImageView!

override func viewWillAppear(animated: Bool) {
    self.imageView.center.y -= view.bounds.height
}
override func viewDidAppear(animated: Bool) {
    UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
        self.imageView.center.y += self.view.bounds.height
    }, completion: nil)
}

此代码确实可以在屏幕上成功移动图像视图,但我不确定如何让它停在我想要的位置。它只是滑出屏幕。目标是将图像从A点移动到B点。如果还有另一种更简单的方法,我很乐意知道。谢谢!

5 个答案:

答案 0 :(得分:3)

在viewWillAppear中添加此项,您将获得动画,问题是autoLayout

override func viewWillAppear(animated: Bool) {
        self.imageview.setTranslatesAutoresizingMaskIntoConstraints(true)
        self.imageview.center.y -= self.view.bounds.height
    }

移动视图框时,最好使用动画antoLayout Constraint

然后将红色约束拖到出口 enter image description here 示例代码

class ViewController: UIViewController{
    @IBOutlet weak var imageview: UIImageView!
    @IBOutlet weak var yConstraint: NSLayoutConstraint!

    override func viewWillAppear(animated: Bool) {
        yConstraint.constant -= self.view.bounds.height;
        self.view.updateConstraintsIfNeeded()
        self.view.layoutIfNeeded()
    }
    override func viewDidAppear(animated: Bool) {
        yConstraint.constant += self.view.bounds.height;

        UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
            self.view.layoutIfNeeded()
            }, completion: nil)
    }
}

答案 1 :(得分:1)

override func viewDidAppear(animated: Bool) {
    var destinationY:CGFloat = self.view.bounds.height / 2 // Your destination Y
    UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
        self.imageView.center.y = destinationY
    }, completion: nil)
}

将它移动太远,将中心放在屏幕中间。

答案 2 :(得分:0)

对于这一行:self.imageView.center.y += self.view.bounds.height

也许让它减少移动? self.imageView.center.y += self.view.bounds.height - 200

答案 3 :(得分:0)

您的实施很好,您只需了解您要更改的数量yself.view.bounds.height指视图控制器视图的高度。事实上,这可能是相当大的,可能是你正在看的整个屏幕高度。因此,您需要决定将其移动到哪一点并进行一些数学运算。假设您想要在它到达屏幕的上边缘时停止它。你可以做一些非常简单的事情:

self.imageView.center.y += (self.view.frame.origin.y - self.imageView.frame.origin.y)

我没有对此进行测试,请以最适合您情况的方式实施。

答案 4 :(得分:0)

override func
viewDidAppear(animated: Bool) {
    super.viewDidAppear( animated )
    let orgY = self.imageView.center.y
    self.imageView.center.y -= view.bounds.height
    UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
        self.imageView.center.y = orgY
    }, completion: nil)
}

保存原点然后去!