2012-08-17 37 views
0

如何在按下按钮时继续运行I​​BAction或某个功能,连续运行功能,直到按钮放开,我如何设置一个按钮(附加了IBAction和UIButton)。正在按下按钮

我应该附加值更改接收器?

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

回答

2

添加调度源伊娃到控制器...

dispatch_source_t  _timer; 

然后,在你着陆动作,创建每隔几秒钟触发一次的计时器。你会在那里做你重复的工作。

如果你所有的工作发生在用户界面中,然后设置队列是

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; 
    } 
} 
0

的UIButton应该调用与触地事件起始方法和呼叫结束法touchUpInside事件

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; 
} 
+0

这while循环中buttonIsDown动作会阻止UI线程,不是吗? – 2012-08-17 01:04:10

+0

如何以编程方式从buttonWasReleased函数结束buttonIsDown函数? – Comradsky 2012-08-17 01:08:33

+0

按照这个答案中的建议进行操作会让你的用户界面完全失去作用。这真是一个可怕的解决方案。 – Till 2012-08-17 01:09:43