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

后端 未结 11 1782
深忆病人
深忆病人 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:37

    Not directly, but some workarounds are possible. Take a look at the following example.

    /// Target-Action helper.
    final class Action: NSObject {
    
        private let _action: () -> ()
    
        init(action: @escaping () -> ()) {
            _action = action
            super.init()
        }
    
        @objc func action() {
            _action()
        }
    
    }
    
    let action1 = Action { print("action1 triggered") }
    
    let button = UIButton()
    button.addTarget(action1, action: #selector(action1.action), forControlEvents: .TouchUpInside)
    

提交回复
热议问题