首页 > 解决方案 > 从多个 UIButtons 制作 UILabel 的集合 - IOS,Swift 4

问题描述

尝试创建多个按钮和多个标签,以便在单击按钮时弹出警报控制器(带有文本字段、确定按钮、清除按钮和取消按钮)。

我试图尽量减少代码量,所以我制作了一组标签:

@IBOutlet var textFieldLabel: [UILabel]!

@IBAction func textFieldTapped(_ sender: UIButton) {
    print("Other11 Button Tapped")
    openOther11Alert()
}

func openOther11Alert() {
    //Create Alert Controller
    let alert = UIAlertController (title: "Other:", message: nil, preferredStyle: UIAlertControllerStyle.alert)

    //Create Clear Action
    let bt = UIAlertAction(title: "CLEAR", style: UIAlertActionStyle.destructive){
        (action) in self.textFieldLabel[0].text = ""}
    alert.addAction(bt)

    //Create Cancel Action
    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
    alert.addAction(cancel)

    //Create OK Action
    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {   (action: UIAlertAction) in print("OK")
    let textfield = alert.textFields?[0]
    print(textfield?.text! as Any)
    self.textFieldLabel[0].text = textfield?.text!
    }
    alert.addAction(ok)

    //Add Text Field
    alert.addTextField { (textfield: UITextField) in
    textfield.text = self.textFieldLabel[0].text
    textfield.placeholder = "Other"
    }

    //Present Alert Controller
    self.present(alert, animated:true, completion: nil)
}

编辑:我希望单击的按钮与标签相对应。目前,我只引用标签数组中的第一个元素(标签):

self.textFieldLabel[0].text

而不是引用“[0]”(第一个标签),我想引用被点击的按钮,这样按钮对应于标签。

知道我是否可以做我正在尝试的事情吗?提前致谢!:)

标签: iosswiftcollectionsuilabeltextfield

解决方案


UIAlertController 文档

根据文档,文本字段属性应该给你一个 UITextFields 数组。根据您的错误消息,您以某种方式获得了 UILabel 数组。也许错误消息正在谈论其他事情?


推荐阅读