2012-08-17 73 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