【发布时间】:2020-04-22 03:40:06
【问题描述】:
我正在向 TextView 动态添加标签和按钮。这是通过循环遍历包含标签名称、按钮名称和按钮功能名称的数组来驱动的。为简洁起见,我已将此处的代码更改为使用硬编码索引而不是循环,并且我没有包含标签和按钮创建函数。标签创建得很好。第一个按钮也创建得很好,因为我将 Button1Clicked 指定为 #selector 参数。仅当我将 Button2Clicked 指定为 #selector 参数时,才能正确创建第二个按钮。如果我尝试在按钮 #selector 参数中引用数组,我会收到编译器错误“'#selector' 的参数不引用 '@objc' 方法、属性或初始化程序”。假设可以使用包含@objc 函数名称的数组作为#selector 的参数,有人可以为我提供适当的语法吗?我正在使用 Swift 5 和 Xcode 11.2。提前感谢您的帮助。
@objc func Button1Clicked(sender: UIButton) {
print("You pressed button 1")
}
@objc func Button2Clicked(sender: UIButton) {
print("You pressed button 2")
}
.
.
.
var labelNames = [UILabel]()
let Label1:UILabel = UILabel()
let Label2:UILabel = UILabel()
labelNames = [Label1, Label2]
var buttonNames = [UIButton]()
let Button1:UIButton = UIButton()
let Button2:UIButton = UIButton()
buttonNames = [Button1, Button2]
let buttonSelectorNames = ["Button1Clicked", "Button2Clicked"]
configureLabel(labelNameIn: labelNames[0],
textIn: "aaaaa",
textColorIn: appColorWhite,
backgroundColorIn: appColorBlue,
yPositionIn: 0)
statusTextview.addSubview(labelNames[0])
configureLabel(labelNameIn: labelNames[1],
textIn: "-- bbbbb",
textColorIn: appColorWhite,
backgroundColorIn: appColorBlue,
yPositionIn: 25)
statusTextview.addSubview(labelNames[1])
configureButton(buttonNameIn: buttonNames[0],
xPositionIn: 0,
yPositionIn: 50,
textIn: "B1",
textColorIn: appColorBlack,
backgroundColorIn: appColorBrightGreen,
textViewIn: statusTextview)
buttonNames[0].addTarget(self,
action: #selector(Button1Clicked),
for: .touchUpInside)
statusTextview.addSubview(buttonNames[0])
configureButton(buttonNameIn: buttonNames[1],
xPositionIn: 100,
yPositionIn: 50,
textIn: "B2",
textColorIn: appColorBlack,
backgroundColorIn: appColorBrightGreen,
textViewIn: statusTextview)
buttonNames[1].addTarget(self,
action: #selector(buttonSelectorNames[1]),
for: .touchUpInside)
statusTextview.addSubview(buttonNames[1])
【问题讨论】:
-
问题在于
buttonSelectorNames是一个字符串数组,而不是一个选择器数组。