OStack程序员社区-中国程序员成长平台

标题: ios - UIButton.addTarget 与 swift 3 和本地功能 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:05
标题: ios - UIButton.addTarget 与 swift 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 方法,因为我正在快速编码!

有人知道方法吗?



Best Answer-推荐答案


这里需要用到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 - UIButton.addTarget 与 swift 3 和本地功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542171/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4