Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 backgroundChange() {
    self.view.backgroundColor = UIColor.blackColor()
    self.view.alpha = 0.55

    let backToOriginalBackground = {
        self.view.backgroundColor = UIColor.whiteColor()
        self.view.alpha = 1.0
    }

    NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(backToOriginalBackground), userInfo: nil, repeats: false)
}

However, this shows an error: Argument of #selector cannot refer to a property.

Of course I can define a new, separate method and move the implementation of the closure to it, but I want to keep it frugal for such a small implementation.

Is it possible to set a closure to #selector argument?

like image 373
Blaszard Avatar asked May 02 '16 13:05

Blaszard


4 Answers

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)
like image 171
werediver Avatar answered Oct 24 '22 06:10

werediver


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!")
})
like image 30
schirrmacher Avatar answered Oct 24 '22 06:10

schirrmacher


As @gnasher729 notes, this is not possible because selectors are just names of methods, not methods themselves. In the general case, I'd use dispatch_after here, but in this particular case, the better tool IMO is UIView.animateWithDuration, because it's exactly what that function is for, and it's very easy to tweak the transition:

UIView.animateWithDuration(0, delay: 0.5, options: [], animations: {
    self.view.backgroundColor = UIColor.whiteColor()
    self.view.alpha = 1.0
}, completion: nil)
like image 11
Rob Napier Avatar answered Oct 24 '22 07:10

Rob Napier


It is now possible. I've created a gist for block-based selectors in Swift 4.

https://gist.github.com/cprovatas/98ff940140c8744c4d1f3bcce7ba4543

Usage:

UIButton().addTarget(Selector, action: Selector { debugPrint("my code here") }, for: .touchUpInside)`
like image 7
Charlton Provatas Avatar answered Oct 24 '22 05:10

Charlton Provatas