0

我如何设置一个按钮(连接了 IBAction 和 UIButton)以在按下按钮时继续运行 IBAction 或功能,连续运行功能直到按钮松开。

我应该附加一个值更改的接收器吗?

简单的问题,但我找不到答案。

4

3 回答 3

3
[myButton addTarget:self action:@selector(buttonIsDown) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(buttonWasReleased) forControlEvents:UIControlEventTouchUpInside];


- (void)buttonIsDown
{
     //myTimer should be declared in your header file so it can be used in both of these actions.
     NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(myRepeatingAction) userInfo:nil repeats:YES];
}

- (void)buttonWasReleased
{
     [myTimer invalidate];
     myTimer = nil;
}
于 2012-08-17T00:59:45.070 回答
2

将调度源 iVar 添加到您的控制器...

dispatch_source_t     _timer;

然后,在您的 touchDown 操作中,创建每隔这么多秒触发一次的计时器。你会在那里做你的重复工作。

如果您的所有工作都发生在 UI 中,则将队列设置为

dispatch_queue_t queue = dispatch_get_main_queue();

然后计时器将在主线程上运行。

- (IBAction)touchDown:(id)sender {
    if (!_timer) {
        dispatch_queue_t queue = dispatch_get_global_queue(
            DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        // This is the number of seconds between each firing of the timer
        float timeoutInSeconds = 0.25;
        dispatch_source_set_timer(
            _timer,
            dispatch_time(DISPATCH_TIME_NOW, timeoutInSeconds * NSEC_PER_SEC),
            timeoutInSeconds * NSEC_PER_SEC,
            0.10 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(_timer, ^{
            // ***** LOOK HERE *****
            // This block will execute every time the timer fires.
            // Do any non-UI related work here so as not to block the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                // Do UI work on main thread
                NSLog(@"Look, Mom, I'm doing some work");
            });
        });
    }

    dispatch_resume(_timer);
}

现在,请务必同时注册 touch-up-inside 和 touch-up-outside

- (IBAction)touchUp:(id)sender {
    if (_timer) {
        dispatch_suspend(_timer);
    }
}

确保销毁计时器

- (void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
        dispatch_release(_timer);
        _timer = NULL;
    }
}
于 2012-08-17T01:50:03.830 回答
0

UIButton 应该使用 touchDown 事件调用开始方法,并使用 touchUpInside 事件调用结束方法

于 2012-08-17T00:42:29.297 回答