OGeek|极客世界-中国程序员成长平台

标题: objective-c - 在 iOS 中触发 Touch Down 的重复事件 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:46
标题: objective-c - 在 iOS 中触发 Touch Down 的重复事件

我正在开发一个应用程序,我希望每隔几秒调用一次方法,同时用户将手指放在按钮上,并在释放时停止。

目前我正在触发 Touch Down 事件的 NSOperation,然后应该调用 NSTimer 以在 2 秒后触发另一个 NSOperation。

然而,只有第一个“runOperation”正在发生;计时器中的不是。

- (IBAction)buttonPressedid)sender
{
    [self doStuff];
}

- (void)runOperation {
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                            selectorselector(doStuff)
                                                                          object:nil];

    [queue addOperationperation];
    [operation release];
}

- (void)doStuff {
    /* stuff goes here */

    [self performSelectorOnMainThreadselector(setTimer) withObject:nil waitUntilDone:YES];
}

- (void)setTimer
{
    timer = [[NSTimer timerWithTimeInterval:2.f target:self selectorselector(runOperation) userInfo:nil repeats:NO] retain];
}

- (IBAction)finishTakingPicturesid)sender {
    [timer invalidate];
    timer = nil;
}



Best Answer-推荐答案


XJones(没有关系)关于计划的计时器和荒谬的间接数量是正确的。但我个人确实喜欢这种用户交互模型的 NSTimer。以下是我将如何实现它。

_buttonTimer is an instance variable,
button is an IBOutlet to the button in question,
touchDown: is connected to the button's TouchDown event.

将按钮添加为 socket 无需使用 BOOL 来跟踪按钮状态,因为按钮知道它的状态。

然后将这些方法添加到您的 UIViewController 子类中。

-(void)helloMe{
    if (self.button.state == UIControlStateNormal){ 
        [_buttonTimer invalidate];
        _buttonTimer = nil
    }
    else {
        NSLog(@"Hello me");
        // Do stuff here
    }
}

- (IBAction)touchDownid)sender {
    _buttonTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selectorselector(helloMe) userInfo:nil repeats:YES];
    [_buttonTimer fire]; // If desired
}

现在运行,您将在按下按钮时在控制台中看到“Hello me”,每两秒一次,直到您松开按钮。

关于objective-c - 在 iOS 中触发 Touch Down 的重复事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172386/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4