gpt4 book ai didi

ios - Swift 中的 UIAlert 会自动消失吗?

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:01 25 4
gpt4 key购买 nike

我有以下代码:

    /// Creates Alerts on screen for user.
func notifyUser(title: String, message: String) -> Void
{
let alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)

alert.addAction(cancelAction)
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated: true,
completion: nil)
}

其中显示以下警报:

enter image description here

我希望警报出现 1-2 秒后自动关闭,而无需单击“确定”或关闭。这可能吗?

最佳答案

是的,这是完全可能的,我认为@Duncan C 方法会很好地工作并且它是不言自明的,所以我将在代码中向您解释@Duncan 方法,另一种方法是使用 Grand Central Dispatch 的延迟(GCD)。

First Approach: Using the NSTimer class

// set the UIAlerController property
var alert: UIAlertController!

func notifyUser(title: String, message: String, timeToDissapear: Int) -> Void
{
alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)

alert.addAction(cancelAction)
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated: true,
completion: nil)

// setting the NSTimer to close the alert after timeToDissapear seconds.
_ = NSTimer.scheduledTimerWithTimeInterval(Double(timeToDissapear), target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
}

Second Approach: Using GCD

// set the UIAlerController property
var alert: UIAlertController!

func notifyUser(title: String, message: String, timeToDissapear: Int) -> Void
{
alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)

alert.addAction(cancelAction)
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated: true,
completion: nil)

// Delay the dismissal by timeToDissapear seconds
let delay = Double(timeToDissapear) * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { [weak self] in
self!.alert.dismissViewControllerAnimated(true, completion: nil)
}
}

然后您可以通过以下方式在任何您想要的地方调用它:

self.notifyUser("Hello", message: "World", timeToDissapear: 3)

希望对你有帮助

关于ios - Swift 中的 UIAlert 会自动消失吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com