简体   繁体   中英

ios - Animate subView's movements inside its superView

I'm using 2 kinds of animation for the round subView: 1. Move the subView += 50 pt. on button clicks (top, bottom, left, right) 2. If the subView hits the bounds of its superView, get the subView back to the previous position (-= 50 pt) AND change its color. So, I'm struggling with constraining the subView withing the superView's boundaries. I don't get how to hold it inside the superView when the frame of subView coincides with the frame of the superView and how to perform the second Animation.

I'm very new to Swift and would appreciate fairly easy explanation ;)

Here's what I get so far.

    @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
            })
        }
}

I might also get the whole concept wrong and that could be the issue too. How to make it working? Thanks in advance to all!

You can try this

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)
        })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM