【问题标题】:how can I pass event through @selector in NSTimer如何通过 NSTimer 中的@selector 传递事件
【发布时间】:2011-07-13 02:59:47
【问题描述】:

//我需要发送事件槽@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); 
        }];
    }
}

【问题讨论】:

    标签: xcode events selector nstimer touches


    【解决方案1】:

    您不能通过选择器传递数据。选择器只是方法的名称,而不是对它的调用。当与计时器一起使用时,您传递的选择器应该接受一个参数,并且该参数将是导致它的计时器。但是,您可以使用userInfo 参数将数据传递给被调用的方法。您在该参数中传递事件,然后使用计时器上的userInfo 方法检索它。

    moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self
                                               selector:@selector(move:)
                                               userInfo:event repeats:YES];
    
    - (void)move:(NSTimer *)theTimer {
        UIEvent *event = [theTimer userInfo];
        ...
    

    【讨论】:

    • 非常感谢它的工作!但发生了一个小错误。当我触摸屏幕时,请参考代码移动功能,图像应该移动到我触摸的点。它工作了很短的时间,图像转到左角(0,0)。你知道为什么吗?无论如何谢谢
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回复。我在 Internet 上找到了有关 NSInvocation 的代码,但我不知道如何使用它。你能解释一下我如何传递参数吗?
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多