iPhone NSTimer运行单一方法

时间:2012-01-21 02:57:51

标签: ios nstimer

我是iPhone的新手,我遇到了这个功能的问题

-(IBAction)changeX {
    [self timere:field1];
    [self timere:field2];
}

这是一个在屏幕上移动uitextfield对象的按钮。问题是我想在第一个字段上运行此方法,完成它然后继续第二个字段。 timere函数使用NSTimer连续移动对象,直到它到达终止的某个点。我还有两个其他功能如下所示。我实际制作的程序要长得多,但目标是相同的,而且代码太长。问题是运行第一个函数然后运行第二个函数。谢谢你的帮助。

-(void)timere:(UITextField*)f1 {

    UITextField*fielder1=f1;
    NSInvocation*timerInvocation = [NSInvocation invocationWithMethodSignature:
                                [self methodSignatureForSelector:@selector(moveP:)]];


    [timerInvocation setSelector:@selector(moveP:)];
    [timerInvocation setTarget:self];
    [timerInvocation setArgument:&fielder1 atIndex:2];   

    timer1 = [NSTimer scheduledTimerWithTimeInterval:0.03 invocation:timerInvocation repeats:YES];
}


-(void) moveP:(UITextField*)f1 {

    UITextField*fielder1=f1;
    fielder1.center = CGPointMake(fielder1.center.x+4, fielder1.center.y);
    if (fielder1.center.x>237) {
        [timer1 invalidate];
    }

}

1 个答案:

答案 0 :(得分:1)

动画UIView对象的标准化方法是使用以下方法。

+ animateWithDuration:delay:options:animations:completion:

如果您不熟悉Objective-C Blocks,这些方法的语法可能有点令人生畏。这是一个用法示例,它移动第一个字段,然后移动第二个字段。

[UIView animateWithDuration:0.3 animations:^{
  [field1 setCenter:CGPointMake(FINAL_CENTER_X1, FINAL_CENTER_Y1)];
} completion:^(BOOL finished) {
  [UIView animateWithDuration:0.3 animations:^{
    [field2 setCenter:CGPointMake(FINAL_CENTER_X2, FINAL_CENTER_Y2)];
  }];
}];

编辑:为了解决您的具体问题,我会做出以下修改:

-(IBAction)changeX {
    [self timere:field1];
}

-(void) moveP:(UITextField*)f1 {

    UITextField*fielder1=f1;
    fielder1.center = CGPointMake(fielder1.center.x+4, fielder1.center.y);
    if (fielder1.center.x>237) {
        [timer1 invalidate];
        // I'm really not sure about the scope of field1 and field2, but
        // you can figure out the encapsulation issues
        if (f1 == field1) {
            [self timere:field2];
        }
    }

}

更通用且确实是低级别的解决方案是拥有状态变量。也许你会有某种NSArray *fields UITextField *int state = 0。如果我在上面的moveP中添加了条件,那么您state++会在[self timere:[fields objectAtIndex:state]]时调用state < [fields count]。无论如何,你的计时器失效代码是正确的。