【问题标题】:UIAlert in Swift that automatically disappears?Swift中的UIAlert会自动消失吗?
【发布时间】:2016-01-29 21:28:40
【问题描述】:

我有以下代码:

    /// 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 秒并自动关闭,而无需单击确定或关闭。这可能吗?

【问题讨论】:

  • 您可以使用 NSTimer 关闭警报控制器
  • 改变 UIAlert 工作方式的用户体验可能不是最好的方法,考虑自定义视图吗?

标签: ios swift uialertcontroller


【解决方案1】:

是的,这完全有可能,我认为@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)

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    这是 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)
        }
    

    【讨论】:

    • 谢谢粉丝。这很简单。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      试试这个代码:

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

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

      scheduledTimerWithTimeInterval

      当前时间设置为 5.0 秒

      【讨论】:

        【解决方案5】:
        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)
            }
        
        }
        

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

        【讨论】:

          【解决方案6】:
           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")
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-04
            • 2016-09-14
            • 1970-01-01
            • 1970-01-01
            • 2014-12-15
            • 2016-08-30
            • 1970-01-01
            • 2013-12-04
            相关资源
            最近更新 更多