2016-11-23 69 views
0

我試圖更新UIAlertController的消息部分中的倒數計時器。我已經嘗試了很多在這裏提出的答案,但沒有喜悅。 我有一個簡單的ViewController來嘗試我想要實現的。在UIAlertController更新倒數計時器的問題

class ViewController: UIViewController { 

var counter:Int = 5 
var timer: NSTimer? 
var label = "" 
var message = "in " 

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

override func viewDidAppear(animated: Bool) { 
    showAlert() 
} 

func showAlert(){ 
    let alertController = UIAlertController(title: "Try again ", message: countDownString(), preferredStyle: .Alert) 

    presentViewController(alertController, animated: true){ 
     self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.decrease), userInfo: nil, repeats: true) 
    } 
} 

func decrease() 
{ 
    var minutes: Int 
    var seconds: Int 
    if(counter > 0) { 
     self.counter -= 1 
     print(counter) // Correct value in console 
     minutes = (counter % 3600)/60 
     seconds = (counter % 3600) % 60 
     label = String(format: "%02d:%02d", minutes, seconds) 
     print(label) // Correct value in console 
    } 
    else{ 
     dismissViewControllerAnimated(true, completion: nil) 
     timer!.invalidate() 
    } 
} 

func alertMessage() -> String { 
    print(message+"\(self.label)") 
    return(message+"\(self.label)") 
} 

func countDownString() -> String { 
    print("\(counter) seconds") 
    return "\(counter) seconds" 
} 

}

計數和標籤都顯示在控制檯中正確的價值觀,但我不能讓他們顯示在UIAlertController值。屏幕截圖顯示了我在視圖控制器中獲得的輸出。

我哪裏錯了?

alertMessage screenshot countDownString screenshot

我使用的Xcode 7.3和雨燕2.2

回答

1

當你實例化你的UIAlertController在下面的代碼,從countDownString()電流值被複制的消息,並且不能這樣

更新
let alertController = UIAlertController(title: "Try again ", message: countDownString(), preferredStyle: .Alert) 

您應該將您的UIAlertController作爲實例屬性存儲,如下所示:

var alertController: UIAlertController! 

改變你的showAlert()代碼:直接

func showAlert(){ 
    alertController = UIAlertController(title: "Try again ", message: countDownString(), preferredStyle: .Alert) 
    presentViewController(alertController, animated: true){ 
     self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.decrease), userInfo: nil, repeats: true) 
    } 
} 

和更新alertController消息在decrease()功能:

func decrease() 
{ 
    var minutes: Int 
    var seconds: Int 
    if(counter > 0) { 
     self.counter -= 1 
     print(counter) // Correct value in console 
     minutes = (counter % 3600)/60 
     seconds = (counter % 3600) % 60 
     alertController.message = String(format: "%02d:%02d", minutes, seconds) 
     print("\(minutes):\(seconds)") // Correct value in console 
    } 
    else{ 
     dismissViewControllerAnimated(true, completion: nil) 
     timer!.invalidate() 
    } 
} 
+1

相同的解決方案。但你打敗了我。 :) –

+0

非常感謝你效果不錯。一個小小的打嗝,它首先顯示5然後00:04,00:03等。我如何將初始變量更改爲顯示00:05以保持其餘? – scooby

+0

甚至不顯示初始值? – scooby