2014年8月6日 星期三

Use timer to delay the method

【說明】

以下將說明如何延遲一段時間在執行method。


【專案開發步驟】

建立專案:

選用Single View Application來建立專案,名為delayMethod。

設計使用者介面:

將UIButton與UILabel加入到Storyboard內,如下圖所示。

設計使用者介面
撰寫按鈕執行的method_Swift:

撰寫@IBAction method,並與Storyboard做連結,如下所示。

<Swift>
@IBAction func changeLabeltext(sender: UIButton) {
    var timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "showLabeltext", userInfo: nil, repeats: false)
}

<Object-C>
- (IBAction)changeLabeltext:(UIButton *)sender {
    [self performSelector:@selector(showLabeltext) withObject:nil afterDelay:2.0];
}
timer會延遲2秒才去執行showLabeltext這個method。

撰寫delay的method,如下所示:

<Swift>
func showLabeltext() {
    theLabel.text = "Hello, World!!"
}

<Object-C>
-(void)showLabeltext {
    self.theLabel.text = @"Hello, World!!";
}
設定Label的文字。


【執行結果】

    

沒有留言:

張貼留言