加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:55:10 所属栏目:百科 来源:网络整理
导读:我的下面的代码会触发警报,但我想触发警报并仅显示操作,具体取决于条件,例如在下面的条件中,如果结果为真,那么我只想显示警报1其他显示警报2 根据条件显示警报动作 var a = loggedInUsernameif ((a?.range(of: "mother")) != nil) { print("true") print ("n
我的下面的代码会触发警报,但我想触发警报并仅显示操作,具体取决于条件,例如在下面的条件中,如果结果为真,那么我只想显示警报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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读