如何在 ActionSheet 中使用 if/else 语句?

How do you use an if/else statement with an ActionSheet?

在我正在创建的应用程序中,我有一个带有一些选项的 ActionSheet。当用户选择一个选项时,我希望标签更改为 he/she 选择的内容。我尝试了一个if/else语句,但我显然没有正确创建它-


@IBAction func showActionSheet(sender: AnyObject) {

    var optionMenu = UIAlertController(title: nil, message: "Choose a Factor", preferredStyle: .ActionSheet)


    let factorActionCageRest = UIAlertAction(title: "Cage Rest", style: .Default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File Deleted")
    })

    let factorActionAfterSurgery = UIAlertAction(title: "After Surgery", style: .Default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File Saved")
    })

    let factorActionTrauma = UIAlertAction(title: "Trauma", style: .Default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File Saved")
    })

    let factorActionSepsis = UIAlertAction(title: "Sepsis", style: .Default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File Saved")
    })

    let factorActionSevereBurn = UIAlertAction(title: "Severe Burn", style: .Default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File Saved")
    })

    let factorCancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        print("Cancelled")
    })


    optionMenu.addAction(factorActionCageRest)
    optionMenu.addAction(factorActionAfterSurgery)
    optionMenu.addAction(factorActionTrauma)
    optionMenu.addAction(factorActionSepsis)
    optionMenu.addAction(factorActionSevereBurn)
    optionMenu.addAction(factorCancelAction)

    if optionMenu.addAction() = factorActionCageRest {
        var factorActionOutput = 1.25
        factorLabel.text = "\(factorActionOutput)"
    }
    self.presentViewController(optionMenu, animated: true, completion: nil)

}

@IBOutlet weak var factorLabel: UILabel!
var factorActionOutput = Float()


}

问题-如何将if/else语句应用到用户的选项中?谢谢!

当用户点击按钮时,该操作的 handler 闭包是 运行。如果你想让事情发生,你需要在更接近处理程序的地方添加代码来实现它。

例如,这就是您可以如何更改第一个操作以在按下按钮时更改 factorLabel 的文本。

let factorActionCageRest = UIAlertAction(title: "Cage Rest", style: .Default, handler: { (alert: UIAlertAction!) -> Void in
    self.factorLabel.text = "File Deleted"
})

我了解到您想在用户选择一个选项时更改标签和变量。所以你可以利用 alertAction 来更新标签

let factorActionCageRest = UIAlertAction(title: "Cage Rest", style: .Default, handler: {
    (alert: UIAlertAction!) -> Void in
        print("File Deleted")
        // Change the label and variable here
})

更新您的 UIAlertAction 处理程序以包含更改标签的代码。

let factorActionCageRest = UIAlertAction(title: "Cage Rest", style: .Default, handler: {
    [weak self] (alert: UIAlertAction!) -> Void in
    print("File Deleted")
    let factorActionOutput = 1.25
    self?.factorLabel.text = "\(factorActionOutput)"
})