使用计时器关闭UIAlertController

问题描述

如果未轻按“确定”按钮,则在几秒钟后关闭UIAlertController.Style.actionSheet

我尝试在显示actionSheet后立即放置一个计时器,以调用一种方法将其关闭,但它不会关闭它。

这是我的代码

func showActionSheet(){
    
    let alert = UIAlertController(title: "Some Tile",message: "Some Message",preferredStyle: UIAlertController.Style.actionSheet)

    alert.addAction(UIAlertAction(title: "OK",style: UIAlertAction.Style.cancel,handler: {
        action in
        self.closeSheetView()
    }))

    self.present(alert,animated: true,completion: nil)

    timer = Timer.scheduledTimer(timeInterval: 2,target: self,selector: #selector(self.closeSheetView),userInfo: nil,repeats: false)
}

@objc func closeSheetView(){
    self.dismiss(animated: true,completion: nil)
}

仅供参考-closeSheetView方法似乎已被调用,但工作表视图没有关闭

解决方法

我只是在我的项目中执行此操作而没有计时器,我使用了delay,也许它会为您服务...!

let alert = UIAlertController(title: "",message: "alert disappears after 5 seconds",preferredStyle: .alert)
self.present(alert,animated: true,completion: nil)

// here it work for 5 sec
let when = DispatchTime.now() + 5
DispatchQueue.main.asyncAfter(deadline: when){
  // your code with delay
  alert.dismiss(animated: true,completion: nil)
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...