0

//我需要提前通过@selector([move:event]) 发送事件槽。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(move:) userInfo:nil repeats:YES];
}

//我的移动函数

- (void)move:(UIEvent *)event { 
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];
    if (location.x > myImageView.center.x){
        [UIView animateWithDuration:0.001 animations:^{
            myImageView.center = CGPointMake(myImageView.center.x+5, myImageView.center.y); 
        }];
    }
    else if (location.x < myImageView.center.x){
        [UIView animateWithDuration:0.001 animations:^{
            myImageView.center = CGPointMake(myImageView.center.x-5, myImageView.center.y); 
        }];
    }
    if (location.y < myImageView.center.y){
         [UIView animateWithDuration:0.001 animations:^{
            myImageView.center = CGPointMake(myImageView.center.x, myImageView.center.y-5); 
        }];
    }
    else if (location.y > myImageView.center.y){
        [UIView animateWithDuration:0.001 animations:^{
            myImageView.center = CGPointMake(myImageView.center.x, myImageView.center.y+5); 
        }];
    }
}
4

2 回答 2

3

You cannot pass data through a selector. A selector is simply the name of a method, not a call to it. When used with a timer, the selector you pass should accept one argument, and that argument will be the timer which caused it. However, you can pass data to the called method using the userInfo parameter. You pass the event in that parameter, and retrieve it using the userInfo method on the timer.

moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self
                                           selector:@selector(move:)
                                           userInfo:event repeats:YES];

- (void)move:(NSTimer *)theTimer {
    UIEvent *event = [theTimer userInfo];
    ...
于 2011-07-13T03:19:31.630 回答
0

如果要使用计时器来触发采用参数的方法,请使用-scheduledTimerWithTimeInterval:invocation:repeats:适当的 NSInvocation 实例来代替采用选择器的方法之一。

也就是说,你将不得不重新考虑你的方法。单个 UIEvent 和 UITouch 对象的生命周期至少与整个触摸序列一样长。根据每个这些类的文档,您不应保留它们或以其他方式在接收它们的方法之外使用它们。如果您需要保存这些对象中的任何一个中的信息以供以后使用,您应该将所需的信息复制到您自己的存储中。

于 2011-07-13T03:35:26.327 回答