![](/img/trans.png)
[英]How to programmatically set a subview's frame to fit it inside its superview?
[英]ios - Animate subView's movements inside its superView
我对圆形子视图使用2种动画:1.移动子视图+ = 50 pt。 单击按钮时(顶部,底部,左侧,右侧)。2.如果subView到达其superView的边界,则将subView返回到先前的位置(-= 50 pt)并更改其颜色。 因此,我正努力将subView与superView的边界约束在一起。 当subView的框架与superView的框架重合时,我不知道如何将其保存在superView中,以及如何执行第二个Animation。
我是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
})
}
}
我可能还会弄错整个概念,这也可能是问题所在。 如何使其运作? 在此先感谢所有人!
你可以试试这个
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)
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.