Benedikt Iltisberger
Benedikt Iltisberger

Reputation: 123

Responder Chain in Swift (nil target in UIButton target)

I have got a problem using the responder chain in swift.

When I setup a buttons target using a nil target like:

someButton.addTarget(nil, action:"addButtonTapped:", forControlEvents: .TouchUpInside)

The action will be send up the responder chain until the action is handled in the controller. So far so good :-)

But I want to intercept the action, execute some code and relay it on to the controller. But I cannot find a way to do this in swift. In ObjC this task is easy to do so I guess there should be a way in swift too.

Thanks in advance for any help :-)

Upvotes: 5

Views: 2867

Answers (2)

orkoden
orkoden

Reputation: 19996

I wanted to show a different view controller after dismissing the current one. The MyContainerViewController container view controller has a function to open a different view controller. Using the responder chain to present a different view controller after dismissing the current one avoids having to keep references or casting the parent view controller. This is especially convenient when using lots of nested child and container view controllers.

class SomeChildViewController: UIViewController {
    @IBAction func closeAndShowSomething(sender: Any?) {}
        let showSelector = #selector(MyContainerViewController.showSomething(_:))
        let viewController: Any? = next?.target(forAction: showSelector, withSender: nil)
        dismiss(animated: true) {
            UIApplication.shared.sendAction(showSelector, to: viewController, from: self, for: nil)
        }
    }
}

Upvotes: 1

Benedikt Iltisberger
Benedikt Iltisberger

Reputation: 123

One of my co-workers gave me the hint to recreate the selector and send it manually again.

let selector = Selector("someButtonTapped:")
let target: AnyObject? = self.nextResponder()?.targetForAction(selector, withSender: button)
UIApplication.sharedApplication().sendAction(selector, to: target, from: self, forEvent: nil)

This recreates the responder chain and relays the new message to the next responder.

I hope that somebody will find this useful.

Upvotes: 5

Related Questions