Can I make #selector refer to a closure in Swift?

后端 未结 11 1828
深忆病人
深忆病人 2020-12-09 15:12

I want to make a selector argument of my method refer to a closure property, both of them exist in the same scope. For example,

func backgroundC         


        
11条回答
  •  情深已故
    2020-12-09 15:43

    I tried this for UIBarButtonItem at least:

    private var actionKey: Void?
    
    extension UIBarButtonItem {
    
        private var _action: () -> () {
            get {
                return objc_getAssociatedObject(self, &actionKey) as! () -> ()
            }
            set {
                objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    
        convenience init(title: String?, style: UIBarButtonItemStyle, action: @escaping () -> ()) {
            self.init(title: title, style: style, target: nil, action: #selector(pressed))
            self.target = self
            self._action = action
        }
    
        @objc private func pressed(sender: UIBarButtonItem) {
            _action()
        }
    
    }
    

    Then you can do this:

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Test", style: .plain, action: {
        print("Hello World!")
    })
    

提交回复
热议问题