如何识别添加了按钮的viewController

如何识别添加了按钮的viewController

本文介绍了如何识别添加了按钮的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"总是失败

superview 是一个 UIView,我不知道如何提取包含 'view' 的 '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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:15