Answer the question
In order to leave comments, you need to log in
Why, when using a timer, does the object return to its initial position on each iteration?
Good day.
Please review the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:4.0f
target:self
selector:@selector(create:)
userInfo:nil
repeats:YES];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *Touch = [[event allTouches]anyObject];
CGPoint location = [Touch locationInView:Touch.view];
if ( (location.x <160)&&(location.y>=496)) {
[UIView setAnimationDuration:0.1f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
if (bounce.center.x>20) {bounce.center = CGPointMake(bounce.center.x - 20 , bounce.center.y); }
}
if ((location.x > 160)&&(location.y>=496)) {
[UIView setAnimationDuration:0.1f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
if (bounce.center.x<300) {bounce.center = CGPointMake(bounce.center.x + 20 , bounce.center.y); }
}
}
-(void)create:(NSTimer*)timer {
CGRect lab = CGRectMake(0, 0, 70, 50);
l = [[UIImageView alloc] initWithFrame:lab];
l.backgroundColor=[UIColor greenColor];
[self.view addSubview:l];
CGRect lab1 = CGRectMake(110, 0, 320, 50);
l1 = [[UIImageView alloc] initWithFrame:lab1];
l1.backgroundColor=[UIColor greenColor];
[self.view addSubview:l1];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
l.center = CGPointMake(35 , 600);
l1.center = CGPointMake(270, 600);
}
Answer the question
In order to leave comments, you need to log in
I solved the problem myself. The bounce object was created in IB and set to the initial position, while the barriers and everything else was created programmatically. As a result, when creating and placing a new barrier, I accessed the UIViewController, and therefore the initial position of the bounce. Therefore, when using the timer, the ball returned to its original position.
Everything started working as it should after I removed bounce from IB and created it with code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question