简体   繁体   中英

How to center a UIView at center of UIButton

I'm using Lottie to add animation on my ViewController . Here is how I'm showing the animation:

    let tapAnimationView = AnimationView(name: "tap")
    tapAnimationView.frame = CGRect(x: 0, y: 0, width: 65, height: 60)
    tapAnimationView.center = myButton.center //CGPoint(x: myButton.center.x, y: self.view.center.y)
    tapAnimationView.loopMode = .loop
    tapAnimationView.animationSpeed = 0.5
    tapAnimationView.contentMode = .scaleAspectFill
    view.addSubview(tapAnimationView)
    tapAnimationView.play(fromFrame: 0, toFrame: 8, loopMode: .loop, completion: nil)

Now what this code does is that it shows animation somewhere close to top left corner. If I replace it with the line in comment it gets close to button but not in the center of the button like I want it to.

Please not that I'm not using AutoLayout Constraints but instead I'm using Autoresizing .

You can try

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
   tapAnimationView.center = myButton.center
}

I am not sure where you add your button into. So get the point of button in self.view

let point = myButton.convert(point: myButton.center, to: self.view)
tapAnimationView.center = point.center

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