如何使用数组更改一组按钮的标题


  • 我有两个IBAction组,每个组有三个按钮
  • 每个按钮都有一个不同的标签-在每组中:1、2和3
  • 我有三个数组,每个数组有三个值

我想按下第一个IBAction的第一个按钮,并根据数组组更改第二个IBAction中三个按钮的标题。

这是代码:

import UIKit
class ViewController: UIViewController {
var firstArray = ["A1","A2","A3"]
var secondArray = ["B1","B2","B3"]
var thirdArray = ["C1","C2","C3"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func greenButtons(_ sender: UIButton) {
if sender.tag == 1 {
//change the title of the grayButtons with the firstArray         
}
if sender.tag == 2 {
//change the title of the grayButtons with the secondArray         
}
if sender.tag == 3 {
//change the title of the grayButtons with the thirdArray         
}
}
@IBAction func grayButtons(_ sender: UIButton) {
}
}

您可以尝试

// create outlet group for each
@IBOutlet weak var greenButtons:[UIButton]! 
@IBOutlet weak var grayButtons:[UIButton]!

绿色按钮内部动作

grayButtons.forEach { $0.setTitle(firstArray[$0.tag - 1],for:.normal) }

您可以将数组构造为,而不是if check

let allArr = [  ["A1","A2","A3"],  ["B1","B2","B3"],["C1","C2","C3"]]

然后

grayButtons.forEach { $0.setTitle(allArr[sender.tag - 1][$0.tag - 1],for:.normal) }

最新更新