简体   繁体   中英

IOS show the label or image position during animation

I am trying to use

UIView.animateWithDuration()

to change the position of a label or an image. It is pretty straightforward. However I also need display the y position of the label in screen during the animation. So the I can see how y position changed during the animation. How can I implement that?

You can get the frame of the moving view from its presentationLayer . You would need to set up an NSTimer to get that value at whatever repeat interval you want.

class ViewController: UIViewController {

    let block = UIView(frame: CGRect(x: 20, y: 100, width: 80, height: 80))

    override func viewDidAppear(animated: Bool) {

        super.viewDidAppear(animated)
        block.backgroundColor = UIColor.redColor()
        self.view.addSubview(block)
        let timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "handleTimer", userInfo: nil, repeats: true)
        UIView.animateWithDuration(5.0, animations: { () -> Void in
             self.block.frame = CGRect(x: 300, y: 400, width: 80, height: 80)
        }) { (finished) -> Void in
            timer.invalidate()
        }
    }

    func handleTimer() {
        println(block.layer.presentationLayer().frame.origin.y)
    }
}

You can move the label by changing it's center.y property. To get the label's top border y position use frame.origin.y. This might help:

 UIView.animateWithDuration(
    0.5,
    animations: {
        label.center.y = <your destination y value> 
        label.text = label.frame.origin.y.description
    },
    completion: nil
    }
)

Hope this helps.

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