通过Swift 3中的IBInspectable传递选择器

时间:2017-05-14 23:00:28

标签: swift custom-controls ibinspectable

我创建了一个自定义控件,我希望在@IBInspectable属性中传递操作,以达到使用UIButton设置@IBAction的相同效果。我应该怎么做呢?

class MyControl: UIButton {
  // Problem with this string approach is 
  //I have no way to know which instance to perform the selector on.
  @IBInspectable var tapAction: String?  

  // set up tap gesture
  ...

  func labelPressed(_ sender: UIGestureRecognizer) {
    if let tapAction = tapAction {
      // How should I convert the string in tapAction into a selector here? 
      //I also want to pass an argument to this selector.
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我真的不知道你为什么要这样,但是......这是我的解决方案:

使用MyActions可以调用的操作创建MyControl类:

class MyActions: NSObject {
    func foo() {
        print("foo")
    }

    func bar() {
        print("bar")
    }

    func baz() {
        print("baz")
    }
}

将您的MyControl课程改为

class MyControl: UIButton {

    @IBInspectable var actionClass: String?
    @IBInspectable var tapAction: String?
    private var actions: NSObject?

    override func awakeFromNib() {
        // initialize actions class
        let bundleName = Bundle.main.bundleIdentifier!.components(separatedBy: ".").last!
        let className = "\(bundleName).\(actionClass!)"

        guard let targetClass = NSClassFromString(className) as? NSObject.Type else {
            print("Class \(className) not found!")
            return
        }

        self.actions = targetClass.init()

        // create tap gesture
        let tap = UITapGestureRecognizer(target: self, action: #selector(pressed(_:)))
        self.addGestureRecognizer(tap)
    }

    func pressed(_ sender: UIGestureRecognizer) {
        actions!.perform(Selector(tapAction!))
    }
}

并设置按钮的属性:

您可以在运行时更改点击操作,例如:

@IBAction func buttonChangeAction(_ sender: Any) {

    buttonMyControl.tapAction = textField.text!
}

也许你可以改变我的代码来传递参数,但是......你想要它吗?