在我的 swift 应用程序中,我有一个带有单个按钮的 UIViewController。
此按钮调用一个函数,该函数调用一个弹出窗口,该弹出窗口在 3 秒后消失。此外,在那之后它会向控制台打印一条消息。该函数的代码如下:
func showAlertMsg(title: String, message: String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
self.presentViewController(alertController, animated: true, completion: nil)
let delay = 3.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
alertController.dismissViewControllerAnimated(true, completion: nil)
print("popup disappeared")
})
}
效果很好,但我想引入一些改进。我想添加一个按钮,该按钮将立即取消此弹出窗口,然后避免在控制台中显示该消息。有没有办法向用户显示这样的弹出窗口?另外 - 有没有一种方法可以在此弹出消息中显示计数器,其中秒数已用完,以显示弹出窗口消失之前还剩多少时间?
您可以使用NSTimer
要减少计数器,请更新警报视图并在计数器达到 0 时关闭警报视图。此代码改编自我的Objective-C 答案 https://stackoverflow.com/questions/36048240/countdown-nstimer-in-title-of-a-uialertcontroller-getting-a-null-instead-of-time/36048730#36048730
class ViewController: UIViewController {
var alertController: UIAlertController?
var alertTimer: NSTimer?
var remainingTime = 0
var baseMessage: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.showAlertMsg("Test Alert", message: "This will disappear in ", time: 5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showAlertMsg(title: String, message: String, time: Int) {
guard (self.alertController == nil) else {
print("Alert already displayed")
return
}
self.baseMessage = message
self.remainingTime = time
self.alertController = UIAlertController(title: title, message: self.alertMessage(), preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
print("Alert was cancelled")
self.alertController=nil;
self.alertTimer?.invalidate()
self.alertTimer=nil
}
self.alertController!.addAction(cancelAction)
self.alertTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.countDown), userInfo: nil, repeats: true)
self.presentViewController(self.alertController!, animated: true, completion: nil)
}
func countDown() {
self.remainingTime -= 1
if (self.remainingTime < 0) {
self.alertTimer?.invalidate()
self.alertTimer = nil
self.alertController!.dismissViewControllerAnimated(true, completion: {
self.alertController = nil
})
} else {
self.alertController!.message = self.alertMessage()
}
}
func alertMessage() -> String {
var message=""
if let baseMessage=self.baseMessage {
message=baseMessage+" "
}
return(message+"\(self.remainingTime)")
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)