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?
- Make sure your text field’s continuous option is turned on.
- Connect the text field’s delegate to your controller.
- Implement
controlTextDidChange:
in your controller. - 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 ];
}
精彩评论