我正在为圆子视图使用2种动画: 1.移动subView + = 50 pt。在按钮上单击(顶部,底部,左侧,右侧) 2.如果subView到达其superView的边界,则将subView返回到先前的位置(-= 50 pt)并更改其颜色。 因此,我正努力将subView与superView的边界约束在一起。当subView的框架与superView的框架重合以及如何执行第二个Animation时,我不知道如何将其保存在superView中。
我是Swift的新手,不胜感激的解释;)
这就是我到目前为止得到的。
@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
})
}
}
我可能还会弄错整个概念,这也可能是问题所在。 如何使其运作?在此先感谢所有人!
答案 0 :(得分:0)
您可以尝试
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)
})
}