【问题标题】:How to pass multiple parameters addTarget?如何传递多个参数addTarget?
【发布时间】:2016-07-08 06:41:23
【问题描述】:

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

这是我当前的代码。

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

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

【问题讨论】:

标签: ios iphone swift


【解决方案1】:

如果您想要多于一个外围传球,那么您可以使用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)
}

【讨论】:

  • 它说:致命错误:在展开可选值时意外发现 nil
  • 谢谢。它正在工作:) 我有一个问题。 sender.withValue 正在打印 Optional("1,2,3,4")。如何删除 Optional()?
  • 哦。 Int(sender.withValue) 正在工作:) 谢谢@mitul marsonia
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2016-04-18
相关资源
最近更新 更多