在其超级视图中为子视图的移动添加动画效果



我为圆形子视图使用了两种动画:1.单击按钮(上、下、左、右(时移动子视图+=50 pt2.如果子视图达到其超视图的边界,则使子视图返回到上一个位置(-=50pt(并更改其颜色。因此,我正在努力将子视图约束在超级视图的边界内。当subView的帧与superView的帧重合时,我不知道如何将其保持在superView中,也不知道如何执行第二个动画。

我是斯威夫特的新手,希望能有一个简单的解释;(

这是我目前为止得到的。

@IBOutlet weak var viewForCircle: UIView! //superView
@IBOutlet weak var upButton: UIButton!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var downButton: UIButton!
@IBOutlet weak var leftButton: UIButton!
//subView
let circleView = UIView() 
let coordinateX = 150
let coordinateY = 150
let width = 150
let height = 150
override func viewDidLoad() {
super.viewDidLoad()
//some buttons stuff is here

self.circleView.frame = CGRect(x: coordinateX, y: coordinateY, width: width, height: height)
self.circleView.backgroundColor = .purple
self.circleView.layer.cornerRadius = circleView.frame.width / 2
self.viewForCircle.addSubview(circleView)

@IBAction func moveUp(_ sender: UIButton) {
positionUp()
}
private func positionUp() {
//the next line is what I'm struggling with
if self.circleView.bounds.origin == self.viewForCircle.bounds.origin {
UIView.animate(withDuration: 1, animations: {
self.circleView.frame.origin.y += 50
self.circleView.backgroundColor = .yellow
})
} else {
UIView.animate(withDuration: 1, animations: {
self.circleView.frame.origin.y -= 50
})
}
}

我也可能误解了整个概念,这也可能是问题所在。如何使其工作?提前感谢所有人!

你可以试试这个

let movDis = self.view.frame.width - circleViewLeftMargin - self.circleView.frame.width
if self.circleView.bounds.origin == self.viewForCircle.bounds.origin {
UIView.animate(withDuration: 1, animations: {
self.circleView.frame = self.circleView.frame.offsetBy(dx:movDis,dy:0)
self.circleView.backgroundColor = .yellow
})
} else {
UIView.animate(withDuration: 1, animations: {
self.circleView.frame = self.circleView.frame.offsetBy(dx:-movDis,dy:0)
})
}

最新更新