繁体   English   中英

Swift 中的 UIAlert 会自动消失?

[英]UIAlert in Swift that automatically disappears?

我有以下代码:

    /// 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)
}

其中显示以下警报:

在此处输入图片说明

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

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

第一种方法:使用NSTimer

// 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)
}

第二种方法:使用 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)

我希望这对你有帮助。

这是 Swift 4 的代码请参考...谢谢

  let alert = UIAlertController(title: "Success", message: "Record Updated Successfully", preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        switch action.style{
        case .default:
            print("default")

        case .cancel:
            print("cancel")

        case .destructive:
            print("destructive")

        }}))
    self.present(alert, animated: true, completion: nil)
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {

        alert.dismiss(animated: true, completion: nil)
    }

当然。 UIAlertController是一种特殊类型的UIViewController 您正在使用presentViewController:animated:completion:显示它。 只需将指向UIAlertController的指针保存到一个实例变量中,启动一个计时器,当计时器触发时,调用dismissViewControllerAnimated:completion: 在这种情况下,您可能希望摆脱 OK 按钮操作,如果您离开 OK 按钮,您将需要测试并确保如果您在计时器触发之前单击 OK 您的代码可以工作。

试试这个代码:

var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "dismissAlert", userInfo: nil, repeats: true)


func dismissAlert()
{
     // Dismiss the alert from here
     alert.dismissViewControllerAnimated(false, completion: nil)

}

我试过了,效果很好。 你可以在里面设置定时器

预定的TimerWithTimeInterval

当前时间设置为 5.0 秒

func alert2 (_ dictKey: String){
    if self.presentedViewController == nil {
        let alertController = UIAlertController(title: nil,     message: dictKey, preferredStyle: .alert )
        alertController.addAction(UIAlertAction(title: "START AGAIN", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction!) in self.returnToStart()}))
        alertController.addAction(UIAlertAction(title: "REQUEST PIN", style: UIAlertActionStyle.default, handler:{(action:UIAlertAction!) in self.pinCreate()
        self.dismiss(animated: false, completion: nil)//This dismisses the alert
        }))
        self.present(alertController, animated: true,completion: nil)
    }

}

这被证明是一个简单的解决方案

 func notifyUser(message: String) -> Void {
  let alert = UIAlertController(title: "", message: message, preferredStyle: UIAlertController.Style.alert)
  present(alert, animated: true, completion: nil)
  DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
   self.dismiss(animated: true)
  }
 }

使用:

  notifyUser(message: "Image Saved")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM