如何在swift 4中从数组中添加标题

问题描述 投票:-1回答:2

我有一个数组,我想知道怎样才能在Swift 4中使用sender.tag为4个UIButton添加标题

这是我的阵列:

let answer: array = ["Black","Green","Red","Gray"]
arrays swift uibutton
2个回答
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并通过tag使你的03,那么当按下按钮时设置的标题将被设置。


如果您的按钮是插座集合的一部分:

@IBOutlet var buttons: [UIButton]!

你可以像这样设置它们(例如在viewDidLoad()中):

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

同样,请务必将tag值设置在answer.indices范围内。


0
投票

导入UIKit

class 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)

}

}

© www.soinside.com 2019 - 2024. All rights reserved.