如何从变量生成标签名称? (如何将字符串转换为 UILabel)

How to generate Labelname from a variable? (how to cast a string to UILabel)

我想根据按下的按钮的标题来引用标签。

我有很多按钮,我通过一个动作将它们连接在一起。我希望能够只引用一个标签,它对应于按下的按钮的名称。

标签名称是:aLabel、bLabel、cLabel ... 按下的按钮标题为 "a"、"b"、"c"...

我正在创建带有我要引用的标签名称的字符串,但我不能将它用作标签名称来更改此特定标签值。

我想用这个字符串来引用相应的标签,更改它的标题、颜色等。

我尝试过转换,寻找一个将字符串更改为 UILabel 的函数。我也在考虑一个带有指向标签的指针的数组,但即使建立一个指向单个标签的指针我也没有成功...

//My code

@IBOutlet weak var a: UIButton!
@IBOutlet weak var b: UIButton!
@IBOutlet weak var c: UIButton!

@IBOutlet weak var aLabel: UILabel!
@IBOutlet weak var bLabel: UILabel!
@IBOutlet weak var cLabel: UILabel!

var currentLabel : String

@IBAction func FieldDisplay(_ sender: UIButton) {
  currentLabel = sender.currentTitle! + "Label"
  currentLabel.text = "OK"
}

//what I tried
(UILabel)currentLabel.text = "OK"
currentLabel = currentLabel.to.UIlabel

删除所有出口并创建 2 个集合

@IBOutlet var allBts: [UIButton]!
@IBOutlet var allLbls: [UILabel]!

然后将所有标签/btns 挂接到每个,并为每个组设置一个标签(lbl1 && btn1 tag = 0,lbl2 && btn2 tag = 1 等等)

@IBAction func FieldDisplay(_ sender: UIButton) {
  allLbls[sender.tag].text = sender.currentTitle! + "Label" 
}

当界面对象像这样以多对关联时——一系列按钮-标签对,正如你所拥有的——通常使用两种方法。一种是为每对分配一个 tag。例如,在故事板中,第一个按钮的标签为 1,第一个标签的标签为 101。然后第二个按钮的标签为 2,第二个标签的标签为 102。依此类推。

所以现在在您的 IBAction 函数中,您查看 sendertag,向其添加 100,然后在 view 上调用 viewWithTag 以找到对应标签。

另一种可能性是使用出口集合。你有一个 array-of-button 插座,而不是三个按钮插座;标签也是如此。现在,在您的 IBAction 函数中,您可以在其数组中获得按钮的 firstIndex;那,如果你已经正确设置它,是 its 数组中相应标签的索引。

你可以使用value(forKey:)方法

@IBAction func buttonTapped(_ sender: UIButton) {
    if let currentLabel = value(forKey: sender.currentTitle! + "Label") as? UILabel {
        currentLabel.text = "OK"
    }
}

https://developer.apple.com/documentation/objectivec/nsobject/1412591-value