问题
I am trying to move a UIView, which is small. My for loop just moves the UIView down 100 points.
This works except it doesn't move until the loop is finished.
I have tried setting
[self.view setNeedsDisplay] and [myView setNeedsDisplay], I have also put the function inside nstimer and nsthread, like seen below
[NSThread detachNewThreadSelector:@selector(doStuff) toTarget:self withObject:nil];
and
[NSTimer scheduledTimerWithTimeInterval:1/15
target:self selector:@selector(doStuff)
userInfo:nil
repeats:NO] ;
But it just does not "animate".
After each move of the view, I do a sleep(1); but still nothing.
Hope anyone can help me.
回答1:
Your for loop blocks the actual redrawing of your view, which happens in the runloop, when your view's drawRect gets called. You have three options (and many more).
Two were suggested by @Darren. Another is to call performSelector:afterDelay passing in the routine that moves the view 100 pixels (the innards of your for loop). At the end of that routine, call performSelector:afterDelay: to requeue the next call. I prefer this to using a timer.
回答2:
You can't use a for loop. You need to set up a repeating timer; each time the timer fires you move the view down x pixels, and you cancel the timer once the view is in its final position.
But you should consider using Core Animation:
[UIView beginAnimations:@"MyAnimation" context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:5.0]; // 5 seconds
CGRect frame = myView.frame;
frame.origin.y += 100.0; // Move view down 100 pixels
myView.frame = frame;
[UIView commitAnimations];
来源:https://stackoverflow.com/questions/1355361/moving-uiview-with-a-for-loop