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?