[英]UIButton.addTarget with swift 3 and local function
我正在嘗試以編程方式生成多個按鈕。 目前,這是我所擁有的:
for i in POIArray {
let newI = i.replacingOccurrences(of: "GPS30", with: "")
let button = UIButton(type: .custom)
button.setImage(UIImage(named: newI), for: .normal)
button.frame.size.height = 30
button.frame.size.width = 30
button.addTarget(self, action: #selector(buttonAction(texte:newI)), for: UIControlEvents.touchUpInside)
XIBMenu?.stackMenuIco.addArrangedSubview(button)
}
和我的職能:
func buttonAction(texte: String) {
print("Okay with \(texte)")
}
當我刪除參數“文本”時,它正在工作。 這些按鈕很好地添加到了堆棧中,但是我需要該參數來傳遞變量。 我收到一個構建時錯誤:
Argument of '#selector' does not refer to an '@objc' method, property, or initializer
是的,謝謝XCode我知道這不是objc方法,因為我正在快速編寫代碼!
有人知道解決方法嗎?
在這里您需要使用objc_setAssociatedObject
在項目中添加擴展名:-
extension UIButton {
private struct AssociatedKeys {
static var DescriptiveName = "KeyValue"
}
@IBInspectable var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
)
}
}
}
}
如何使用 :-
//let newI = i.replacingOccurrences(of: "GPS30", with: "")
button?.descriptiveName = "stringData" //newI use here
如何獲取參數:
func buttonAction(sender: UIButton!) {
print(sender.descriptiveName)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.