ios - UIAlertAction 处理程序在错误的时间调用?

标签 ios swift uialertview

我有一个如下所示的函数:

@IBAction func showAlert(){

//Some irrelevant code

let alert = UIAlertController(title: "Some Title", message: "Some Message", preferredStyle: .alert)

let action = UIAlertAction(title: "Close this alert", style: .default, handler: {
    action in
        self.startNewRound()
    })


alert.addAction(action)

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

}

这是updateLabels():

updateLabels() { 
targetLabel.text = String(targetValue)
scoreLabel.text = String(score)
roundLabel.text = String(round)

以下是一些全局变量:

var currentValue: Int = 0
@IBOutlet weak var targetLabel: UILabel!
var targetValue: Int = 0
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var roundLabel: UILabel!
var round: Int = 0

这里是startNewRound():

func startNewRound() {
targetValue = Int(arc4random_uniform(100)) + 1
currentValue = 50
slider.value = Float(currentValue)
round += 1
updateLabels()
} 

这个想法是,只要按下主视图 Controller 中的某个按钮,就会调用此函数,然后弹出警报。一旦用户关闭警报,就会调用 startNewRound()

但是,在当前代码中,只有在用户关闭警报后再次按下 View Controller 按钮时才会调用 startNewRound()。如何让 startNewRound() 在警报关闭后立即运行?

最佳答案

试试这个。

@IBAction func showAlert(){

    //Some irrelevant code

    let alertController = UIAlertController(title: "Some Title", message: "Some Message", preferredStyle: .alert)

    let closeAction = UIAlertAction(title: "Close this alert", style: UIAlertActionStyle.default) {
        UIAlertAction in
            self.startNewRound()
    }

    alertController.addAction(closeAction)

    self.present(alertController, animated: true, completion: nil)
}

关于ios - UIAlertAction 处理程序在错误的时间调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119786/

相关文章:

ios - 更改 UISlider x 和 y 位置

swift - 协议(protocol)扩展中函数命名的段错误 11

ios - 是否可以在 UIAlertView 上垂直放置 2 个按钮?

iphone - 查看一切之上 : UIWindow subview VS UIViewController subview

ios - 检查 NSURL 是否是 Assets

ios - 如何为 Apple Store(ionic 应用程序)正确设置英语以外的其他语言

ios - 如何使用 setObject Swift 2.0 实现基于时间的 NSCache

objective-c - [AVAssetWriterInput requestMediaDataWhenReadyOnQueue :usingBlock:] 的内存问题

swift - 如何在 SwiftUI 中使用 Picker 设置文本字段作为输入

objective-c - 从 uialertview 按钮打开一个 uiviewcontroller