How to identify the viewController a button has been added onto?(如何识别已添加按钮的 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
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何识别已添加按钮的 viewController?
基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01