我正在尝试以编程方式生成多个按钮。目前,这是我所拥有的:

    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方法,因为我正在快速编写代码!

有人知道解决方法吗?

最佳答案

在这里您需要使用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)
}

关于ios - 带有swift 3和本地功能的UIButton.addTarget,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38542171/

10-09 16:19