在 iOS 開發中,若需要讓提示框短暫顯示後自動消失,NSTimer 是很直接的工具。本文以一個小範例說明如何安排定時器,讓提示框在約三秒後自動關閉。
使用 NSTimer 時,通常需要掌握三個重點:
@selector 指定到時間要呼叫的方法。- (void)performDismiss:(NSTimer *)timer
{
[baseAlert dismissWithClickedButtonIndex:0 animated:NO];
[baseAlert release];
baseAlert = NULL;
}
- (void)presentSheet
{
baseAlert = [[UIAlertView alloc] initWithTitle:@"Alert"
message:@"Message to user"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0f
target:self
selector:@selector(performDismiss:)
userInfo:nil
repeats:NO];
[baseAlert show];
}
這個寫法適合只需要短暫停留的提示訊息。若要在新專案中使用,也可將 UIAlertView 替換為 UIAlertController,並保留相同的定時關閉邏輯。