2016-07-23 5 views
1

프로그래밍 방식으로 여러 개의 단추를 생성하려고합니다. 순간을 위해, 여기에 내가있어 무엇 :swift 3 및 로컬 함수 UIButton.addTarget

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 

예 당신은 내가이 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