如何在Swift 4数组中的按钮中添加标题

时间:2018-12-27 13:25:00

标签: arrays swift uibutton

我有一个数组,我想知道如何在Swift 4中使用sender.tag向4个UIButton添加标题

这是我的数组:

let answer: array = ["Black","Green","Red","Gray"]

2 个答案:

答案 0 :(得分:0)

使用sender.tag作为answer数组的索引。使用guard确保sender.tag是有效的索引(这样就不会崩溃):

let answer = ["Black", "Green", "Red", "Gray"]

@IBAction func buttonPressed(_ sender: UIButton) {
    guard answer.indices.contains(sender.tag) else { return }

    sender.setTitle(answer[sender.tag], for: .normal)
}

如果将按钮连接到此@IBAction,并设置tag03,则当按钮位于按下。


如果您的按钮属于插座系列:

@IBOutlet var buttons: [UIButton]!

您可以这样设置它们(例如,在viewDidLoad()中)

buttons.forEach { $0.setTitle(answer[$0.tag], for: .normal)

同样,请确保将tag的值设置在answer.indices范围内。

答案 1 :(得分:0)

导入UIKit

ViewController类:UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let array = ["Black","Green","Red","Gray"]

    var oldButton = UIButton()

    for i in 1...array.count {

        let button = UIButton()

        if i == 1 {

            button.frame = CGRect(x: 10, y: 40, width: 90, height: 20)
            button.tag = i
            button.addTarget(self, action: #selector(ViewController.selctorButton(_:)), for: UIControl.Event.touchDown)
            button.setTitle(array[button.tag - 1], for: .normal)

        }

        else {

            button.frame = CGRect(x: oldButton.frame.maxX + 10, y: 40, width: 90, height: 20)
            button.tag = i
            button.addTarget(self, action: #selector(ViewController.selctorButton(_:)), for: UIControl.Event.touchDown)
            button.setTitle(array[button.tag - 1], for: .normal)

        }

        button.backgroundColor = UIColor.black
        view.addSubview(button)
        oldButton = button

    }
}

@objc func selctorButton(_ sender : UIButton){

    print(sender.tag)

}

}