2

I'm trying to generate multiple buttons programmatically. For the moment, here is what I've got :

    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)

    }

and my function :

        func buttonAction(texte: String) {
            print("Okay with \(texte)")
        }

When I remove the parameter 'texte', it's working. The buttons are well added to the stack but I need that parameter to pass a variable. I get a buildtime error :

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

Yes thank you XCode I know that it's not an objc method, because I'm coding in swift!

Anyone knows a way around ?

petaire
  • 495
  • 1
  • 10
  • 23
  • Possible duplicate of [Attach parameter to button.addTarget action in Swift](http://stackoverflow.com/questions/24814646/attach-parameter-to-button-addtarget-action-in-swift) – KTPatel Dec 22 '16 at 09:46

1 Answers1

0

Here you need to use objc_setAssociatedObject

Add extension in project:-

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

How to use :-

//let newI = i.replacingOccurrences(of: "GPS30", with: "")
button?.descriptiveName = "stringData" //newI use here

How to get parameter :-

func buttonAction(sender: UIButton!) {
            print(sender.descriptiveName)
}
Mitul Marsoniya
  • 5,272
  • 4
  • 33
  • 57