How to identify the viewController a button has be

2020-02-16 06:01发布

I want to know what was the name of the viewController the the button was tapped. I've already looked into the answer provided here. But I believe won't work if I have different containerViews on the screen...where the viewController for each button may be different. Hence I need a different solution.

So I wrote this function to recursively look until it finds a UIViewController.

extension UIView{
    func getTypeOfMyViewController() -> UIViewController.Type?{
        if let _super = superview as? UIViewController{ // logically wrong!
            return type(of:_super)
        }else if let _super = superview{
            return _super.getTypeOfMyViewController()
        }else{
            assertionFailure("everything should end up being on some viewController")
            return nil
        }
    }
}

The only problem is this line:

if let _super = superview as? UIViewController{

It gives me the following warning:

Cast from 'UIView?' to unrelated type 'UIViewController' always fails

superview is a UIView and I don't know how to extract the 'viewController' which contains the 'view'.

Question1: So How can I do that?

Additionally I would like to use the getTypeOfMyViewController function as such:

extension UIButton{
    open override var accessibilityLabel: String?{
        get {
            return "\(getTypeOfMyViewController.self): \(titleLabel?.text ?? "Null")"
        }
        set{
            // nothing particular
        }
    }
}

I'm doing this because I want to create a unique identifier for all button taps in my logging system.

Question2: Does Swift offer any easier solution to this?

1条回答
beautiful°
2楼-- · 2020-02-16 06:24

A view controller is not a view, so it can never be a superview. You have the right idea, but you're looking at the wrong hierarchy. What you want is not the view hierarchy but the responder chain.

Walk up the responder chain until you come to the view controller:

var r : UIResponder = theButton
repeat { r = r.next! } while !(r is UIViewController)
let vc = r as! UIViewController
查看更多
登录 后发表回答