开发者

Updating UILabel and UIButton immediately

开发者 https://www.devze.com 2022-12-29 05:50 出处:网络
In a project, I change a UIL开发者_StackOverflow中文版abel\'s text with setText, a UIButton\'s color and after that do a time consuming calculation, followed by an animation.

In a project, I change a UIL开发者_StackOverflow中文版abel's text with setText, a UIButton's color and after that do a time consuming calculation, followed by an animation.

However, the text's and color's change is reflected after the calculation is executed (and before the animation begins) however I want to reflect the changes immediately before calculation (as you guess it is a waiting text)

How can I achieve this?


Move the calculation off the main thread.

All drawing is performed when the run loop gets time. If you are performing a calculation on the main thread, you are blocking the run loop and thus blocking drawing. When the calculation finishes, use performSelectorOnMainThread to start the animation or whatever else needs to happen in the UI when the calculation completes.

Edit:

A quick way to perform your calculation on the main thread but give the run loop a chance to update UI is with a delay call. Use a delay of 0.1 seconds or so. You can do essentially the same thing with an NSTimer. This is in NSRunLoop.h

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;


If you do not need a responsive interface while calculating the easiest way is to avoid threads: Put the time consuming calculation in its own method and start that using [calculator performSelector:@selector(calculateThis:) withObject:myArgument afterDelay:0].

This will allow the run loop to update you interface changes and then starts the calculation on the main thread (blocking it).


Start the calculation running in a background thread.


I think your best bet is to perform your time consuming animation in a background thread. This way your main UI thread will not block and the text and colour will change straight away. Also your UI will remain responsive while you perform your calculation.

In general it is a good idea not to block the main thread with hefty calculations as this gives the appearance of the app not being very responsive.

0

精彩评论

暂无评论...
验证码 换一张
取 消