2016-07-23 52 views
1

我試圖以編程方式生成多個按鈕。目前,這裏是我的本錢:UIButton.addTarget與迅速3和本地功能

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)") 
     } 

當我刪除了參數「texte」,它的工作。按鈕很好地添加到堆棧,但我需要該參數來傳遞一個變量。我得到一個錯誤聯編:

Argument of '#selector' does not refer to an '@objc' method, property, or initializer 

是感謝你的Xcode我知道,這不是一個objc方法,因爲我在迅速編碼!

任何人都知道一個方法嗎?

+0

可能重複e [將參數附加到Swift中的button.addTarget動作](http://stackoverflow.com/questions/24814646/attach-parameter-to-button-addtarget-action-in-swift) – KTPATEL

回答

0

在這裏,您需要在項目中使用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) 
} 
+0

感謝它的工作!雖然我認爲這是一個迅速的缺陷,你不覺得嗎? – petaire