如何识别已添加按钮的viewController? [英] How to identify the viewController a button has been added onto?

查看:88
本文介绍了如何识别已添加按钮的viewController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道按钮被点击时viewController的名字是什么.我已经在此处调查了提供的答案.但是我相信如果我在屏幕上使用不同的containerViews是行不通的...每个按钮的viewController可能不同.因此,我需要一个不同的解决方案.

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.

因此,我编写了此函数以递归查找,直到找到UIViewController.

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
        }
    }
}

唯一的问题是这一行:

if let _super = superview as? UIViewController{

它给了我以下警告:

是否从"UIView"投射?无关类型"UIViewController"总是失败

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

superviewUIView,我不知道如何提取包含视图" 的'viewController'.

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

问题1:那么我该怎么做?

此外,我想像这样使用getTypeOfMyViewController函数:

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.

问题2: Swift是否可以为此提供任何更简单的解决方案?

Question2: Does Swift offer any easier solution to this?

推荐答案

视图控制器不是视图,因此它永远不能是超级视图.您有正确的主意,但您选择的是错误的层次结构.您想要的不是视图层次结构,而是响应者链.

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

这篇关于如何识别已添加按钮的viewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆