您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS NSTimer 定時器實作:三秒後自動關閉提示框

編輯:iOS 開發綜合

在 iOS 開發中,若需要讓提示框短暫顯示後自動消失,NSTimer 是很直接的工具。本文以一個小範例說明如何安排定時器,讓提示框在約三秒後自動關閉。

定時器的關鍵參數

使用 NSTimer 時,通常需要掌握三個重點:

  • 時間間隔:以浮點數表示,例如 3.0 代表三秒。
  • 事件代理:指定接收通知的物件。
  • 事件處理方法:透過 @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,並保留相同的定時關閉邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved