Swift 5在uialertController中更好地使用完成处理程序?

时间:2019-04-18 11:09:45

标签: swift alert

对关闭和竞争Hanlder关于警报的一些说明。这里哪种用法更好?如果我应该在第二种情况下如何使用“动作”?结果似乎是相同的,它可以工作,但是我想更好地理解为什么。

import UIKit

struct exapleStruct {
    var inHotel = true
}

class ViewController : UIViewController {

    var exapleStruct : exapleStruct!
    var detailTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()


        let myAlertController = UIAlertController(title: "Add or Change value", message: "", preferredStyle: .alert)

        //firstExample
        let booleanChange = UIAlertAction(title: "change", style: .default, handler: self.handlerForBool)
        //second exampple how shoukld I use "action" ?? why is it there?
        let booleanChange2 = UIAlertAction(title: "change", style: .default) { (action) in
            print(self.exapleStruct.inHotel)
            self.detailTable.reloadData()
        }


        myAlertController.addAction(booleanChange)
        present(myAlertController, animated: true, completion: nil)

    }

func handlerForBool(alertARgument: UIAlertAction!) {
    print(exapleStruct.inHotel)
    self.detailTable.reloadData()
}


}

1 个答案:

答案 0 :(得分:0)

使用此

let booleanChange2 = UIAlertAction.init(title: "option1", style: .default, 
    handler: handlerForBool(alertARgument:))
let booleanChange3 = UIAlertAction.init(title: "option2", style: .default, 
    handler: handlerForBool(alertARgument:))

func handlerForBool(alertARgument: UIAlertAction!) {
    print(exapleStruct.inHotel)
    self.detailTable.reloadData()
}

在需要多个AlertActions的相同操作时很有用,它具有功能可重用性