通过UIView对象获取该对象所属的UIViewController

简介: 通过UIView对象获取该对象所属的UIViewController

通过UIView对象获取该对象所属的UIViewController可以使用UIResponder的nextResponder方法获得,UIView类继承于UIResponder,因此可以直接使用。

   根据文档描述,如果View有view controller,则通过nextResponder方法返回,如果没有则返回superview。

下面是英文原文:

if the view has a view controller, it is returned by nextResponder.

If there is no view controller, the method will return the superview

   相关代码如下:遍历该View的树形结构,获取到其所属的ViewController

- (UIViewController*)GetViewController:(UIView*)uView
{
    for (UIView* next = [uView superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}
相关文章
|
2月前
|
Swift iOS开发 开发者
什么是 UIViewController 生命周期?
什么是 UIViewController 生命周期?
33 5
|
2月前
|
iOS开发 容器
什么是 UINavigationController 和 UITabBarController?它们有什么作用?
什么是 UINavigationController 和 UITabBarController?它们有什么作用?
26 2
|
Swift
Swift - 如何让UIView,UILabel和UIImageView之间类型互相转化
Swift - 如何让UIView,UILabel和UIImageView之间类型互相转化
124 0
|
开发工具
UIView的clipsTobounds属性
UIView的clipsTobounds属性
101 0
UIView的clipsTobounds属性
|
容器
UIView与CALayer的关系
UIView与CALayer的关系
434 0
一个重要的类 CALayer
一个重要的类CALayer —— 基本概览(一)一个重要的类CALayer —— 其与UIView的区别(二)一个重要的类CALayer ——主要属性及其在显示图片中的简单应用(三)
764 0
|
iOS开发
iOS开发之UIView与UIViewController的生命周期总结
iOS开发中,创建View常见的两种方式一个是纯代码,一个是借助于XIB;创建ViewController常见的也有两种方式一个是纯代码,一个是借助于StoryBoard。
1247 0
UIViewController生命周期
原文出自:http://blog.csdn.net/duanyipeng/article/details/7106015 原文发布时间为:2012-08-15 本文作者:vinoYang 本文来自云栖社区合作伙伴CSDN博客,了解相关信息可以关注CSDN博客。
870 0