使用计时器关闭 UIAlertController
Dismiss UIAlertController with timer
如果未点击“确定”按钮,几秒钟后关闭 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
方法似乎被调用但 sheet 视图没有关闭。
我只是在我的项目中不使用计时器来完成我使用延迟,也许它对你有用......!
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)
}
如果未点击“确定”按钮,几秒钟后关闭 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
方法似乎被调用但 sheet 视图没有关闭。
我只是在我的项目中不使用计时器来完成我使用延迟,也许它对你有用......!
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)
}