ios - 如何传递多个参数addTarget?

标签 ios iphone swift

我需要传递两个参数。我怎样才能通过 addTarget action。如果可能,我需要执行哪些更改?

这是我当前的代码。

button.tag = numbers[index];
button.addTarget(self, action: #selector(ViewController.buttonClicked(_:)), forControlEvents:UIControlEvents.TouchUpInside)

func buttonClicked(sender: UIButton){
     print(sender.tag)
}

最佳答案

如果你想要不止一个外围 channel ,那么你可以使用 objc_setAssociatedObject
任何东西都会被传递,比如 Dictionary,Array,String,Int.

import ObjectiveC

extension UIButton {
private struct AssociatedKeys {
    static var WithValue = "KeyValue"
}

@IBInspectable var withValue: String? {
    get {
        return objc_getAssociatedObject(self, &AssociatedKeys.WithValue) as? String
    }
    set {
        if let newValue = newValue {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.WithValue,
                newValue as NSString?,
                objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
            )
        }
    }
}
}

你需要使用上面的扩展:-

导入 ObjectiveC

button.tag = numbers[index];
    button.addTarget(self, action: #selector(ViewController.buttonClicked(_:)), forControlEvents:UIControlEvents.TouchUpInside)

    //set velue
   button.withVelue = "1,2,3,4"

func buttonClicked(sender: UIButton){

     print(sender.withVelue)
}

关于ios - 如何传递多个参数addTarget?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38260390/

相关文章:

iphone - if else 语句混淆 Objective-C

xcode - 命令/usr/bin/codesign失败,退出代码为1

iphone - 奇怪的 UIImageview 远程图像加载行为

iphone - 如何给 UIButton 着色?

ios - Swift 中的推送通知

ios - App Store - 帮助回答 "Missing Compliance"(使用 Expo + Firebase)

ios - didBeginContact() 在接触发生之前调用

iphone - 如何在Apple Aurio Touch( Audio Session 示例)应用程序中使输出静音?

ios - 解析结果的登录验证

ios - 从容器 View 调用父 View Controller 函数