问题
I am learning to program for the iPhone and am making a simple ball bounce game where a ball bounces upward on platforms. The game works and the ball seemingly moves upward when it reaches the top 1/4 of the screen (the platforms on the screen move down, similar to Doodle Jump), however I am having problems when trying to implement a score counter. When the ball reaches the top 1/4 of the screen, I add to the score and run the following two lines of code:
NSString *nssScore = [NSString stringWithFormat:@"%i", score];
lblScore.text = nssScore;
lblScore is a UILabel and linked to a text label in the view. Every time the text updates on the screen, the ball and all platforms return to their starting positions, however the ball maintains its velocity. When running the debugger line by line, I can run both lines of code without error, the problem lies when the text is changed on the screen in the next refresh. The main game loop and frame-rate is run with the following line of code:
[NSTimer scheduledTimerWithTimeInterval:1.0/60
target:self selector:@selector(gameLoop) userInfo:nil repeats:YES];
回答1:
This is a problem with layout constraints. The problem doesn't actually have anything to do with the label, it's just that setting the value of the label triggers a redrawing (or layout, I'm not sure exactly which method is called). The simplest solution is to turn off auto layout in IB (from the left most tab on the right side of the screen). Alternately, you can move the ball by animating its constraints, rather than setting frames.
来源:https://stackoverflow.com/questions/15103737/uilabel-causing-other-objects-to-reset-position-on-ios