[英]Primitive type parameters in Swift Selector function
我想向我的 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.