Swift Selector函数中的基本类型参数



我想添加动态数量的按钮到我的VC。我在循环我的按钮数组模型并实例化UIButtons。问题在于将目标添加到这些按钮中。我想在添加目标时将字符串传递给选择器,但是Xcode编译器不允许我这样做

'#selector'的参数没有引用'@objc'方法、属性或初始化项

@objc func didTapOnButton(url: String) { }
let button = UIButton()
button.addTarget(self, action: #selector(didTapOnButton(url: "Random string which is different for every bbutton ")), for: .touchUpInside)

除了使用自定义UIButton之外,还有其他解决方案吗

我认为这是不可能做到的,你可以这样尝试:

var buttons: [UIButton: String] = []
let button = UIButton()
let urlString = "Random string which is different for every button"
buttons[button] = urlString
button.addTarget(self, action: #selector(didTapOnButton), for: .touchUpInside
@objc func didTapOnButton(sender: UIButton) { 
let urlString = self.buttons[sender]
// Do something with my URL
}

我记得UIButton是可哈希的…

另一个选择是扩展UIButton来保存你想要的信息:

extension UIButton {
private static var _urlStringComputedProperty = [String: String]()
var urlString String {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return Self._urlStringComputedProperty[tmpAddress]
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
Self._urlStringComputedProperty[tmpAddress] = newValue
}
}
}
let button = UIButton()
button.urlString = "Random string which is different for every button"
button.addTarget(self, action: #selector(didTapOnButton), for: .touchUpInside
@objc func didTapOnButton(sender: UIButton) { 
let urlString = sender.urlString
// Do something with my URL
}