NSTimer blocks other animations

2019-05-31 02:24发布

问题:

Description

I have a NSTimer that updates an UILabel every second. I have another UIImageView that slides in the screen when a UIButton is pressed.

Issue

The problem is that when the NSTimer updates the UILabel, the animation of the UImageView stops from completing.

Question

Please can you tell me how can i update the timer without messing with the other animations?

回答1:

This is a common symptom of having auto layout turned on but are probably trying to slide it across the screen by adjusting the frame or center. Auto layout is a iOS 6+ feature that controls the location and size of various UIView elements. Unfortunately, when you have auto layout on, every time you change a label's value, it will reapply the constraints that dictate where the label should be positioned, defeating your attempts to animate it.

Two solutions:

  1. Turn off auto layout by opening up your storyboard or NIB, click on the first "document inspector" tab on the rightmost panel, and then uncheck "Use Autolayout".

  2. If you want to use autolayout, animate the moving of the control by changing constraints rather than changing frame or center. See here for an example of how you can create an IBOutlet for a constraint and then change that constraint programmatically in an animateWithDuration block.

References:

  • Cocoa Auto Layout Guide

  • Introduction to Auto Layout for iOS and OS X

  • Best Practices for Mastering Auto Layout

  • Auto Layout by Example