简体   繁体   English

带有Swift 3和本地功能的UIButton.addTarget

[英]UIButton.addTarget with swift 3 and local function

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! 是的,谢谢XCode我知道这不是objc方法,因为我正在快速编写代码!

Anyone knows a way around ? 有人知道解决方法吗?

Here you need to use objc_setAssociatedObject 在这里您需要使用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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM