开发者

Performing an action on end editing

I have a text field in my Objective-C Mac app.

This is what I want: when I stop writing in the text field for more than 5 seconds, it开发者_如何学C runs something. Is this possible?

If so, can someone explain how?


  1. Make sure your text field’s continuous option is turned on.
  2. Connect the text field’s delegate to your controller.
  3. Implement controlTextDidChange: in your controller.
  4. Start a timer (and invalidate the old one) each time you receive controlTextDidChange:.

Here’s an example:

- (void)controlTextDidChange:(NSNotification *)notification
{
   if (timeoutTimer != nil) {
      [timeoutTimer invalidate];
      [timeoutTimer release];
      timeoutTimer = nil;
   }

   timeoutTimer = [[NSTimer 
      scheduledTimerWithTimeInterval:5.0
      target:self
      selector:@selector(doSomething)
      userInfo:nil
      repeats:NO] retain];
}


Use -performSelector:withObject:afterDelay:, and cancel the perform request if the user begins typing again. Here's a crude example:

- ( void )controlTextDidChange: (NSNotification *)notification
{
    if ( [ notification object ] != myTextField ) {
        return;
    }

    [ NSObject cancelPreviousPerformRequestsWithTarget: self
               selector: @selector( userStoppedEditing: )
               object: myTextField ];
    [ self performSelector: @selector( userStoppedEditing: )
           withObject: myTextField
           afterDelay: 5.0 ];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜