按下按钮时

时间:2012-08-17 00:39:41

标签: iphone objective-c ios xcode ipad

如何设置按钮(IBAction和UIButton附加)以在按下按钮时继续运行I​​BAction或功能,连续运行功能直到按钮松开。

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

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

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);
}

现在,请确保注册内部触摸和外部触摸

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

确保销毁计时器

- (void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
        dispatch_release(_timer);
        _timer = NULL;
    }
}

答案 2 :(得分:0)

UIButton应使用touchDown事件调用启动方法,并使用touchUpInside事件调用结束方法