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

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

    So my answer to having a selector be assigned to a closure in a swift like manner is similar to some of the answers already, but I thought I would share a real life example of how I did it within a UIViewController extension.

    fileprivate class BarButtonItem: UIBarButtonItem {
      var actionCallback: ( () -> Void )?
      func buttonAction() {
        actionCallback?()
      }
    }
    
    fileprivate extension Selector {
      static let onBarButtonAction = #selector(BarButtonItem.buttonAction)
    }
    
    extension UIViewController {
      func createBarButtonItem(title: String, action: @escaping () -> Void ) -> UIBarButtonItem {
        let button = BarButtonItem(title: title, style: .plain, target nil, action: nil)
        button.actionCallback = action
        button.action = .onBarButtonAction
        return button
      }
    }
    
    // Example where button is inside a method of a UIViewController 
    // and added to the navigationItem of the UINavigationController
    
    let button = createBarButtonItem(title: "Done"){
      print("Do something when done")
    }
    
    navigationItem.setLeftbarButtonItems([button], animated: false)
    

提交回复
热议问题