微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift:iOS根据条件显示警报动作

我的下面的代码会触发警报,但我想触发警报并仅显示操作,具体取决于条件,例如在下面的条件中,如果结果为真,那么我只想显示警报1其他显示警报2

根据条件显示警报动作

var a = loggedInUsername

if ((a?.range(of: "mother")) != nil) {
    print("true")
    print ("name:",loggedInUsername)
    let action1 = UIAlertAction(title: "Delete",style: .default,handler: { (action) -> Void in
        print("ACTION 1 selected!")
    })

    let action2 = UIAlertAction(title: "Approve Chore",handler: { (action) -> Void in
    })

解决方法

如果你想有条件地显示UIAlertAction.如果你的条件是真的,你想要显示action1,如果条件是假,你想要显示action2.

试试这个.

let alert = UIAlertController(title: AppName,message: "YOUR MESSAGE",preferredStyle: .alert)
    alert.view.tintColor = Colors.NavTitleColor
    let action1 = UIAlertAction(title: "Delete",handler: {(_ action: UIAlertAction) -> Void in

    })
    let action2 = UIAlertAction(title: "Approve Chore",style: .cancel,handler: {(_ action: UIAlertAction) -> Void in

    })

    if ((a?.range(of: "mother")) != nil) {
        alert.addAction(action1)
    }
    else {
        alert.addAction(action2)
    }

    present(alert,animated: true) {() -> Void in }

如果你想在UIAlertAction标题之前添加Image而不是使用下面的代码.

let alert = UIAlertController(title: "Title",preferredStyle: .alert)
    alert.view.tintColor = Colors.NavTitleColor

    let image1 = UIImage(named: "attendance")
    let action1 = UIAlertAction(title: "Delete",handler: nil)
    action1.setValue(image1,forKey: "image")

    let image2 = UIImage(named: "mail")
    let action2 = UIAlertAction(title: "Approve Chore",handler: nil)
    action2.setValue(image2,forKey: "image")

    alert.addAction(action1)
    alert.addAction(action2)

    present(alert,animated: true) {() -> Void in }

看起来像下图.

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐