获取UIView的视图控制器(Swift)
2016-03-26 11:29
495 查看
UIView继承自UIResponder,可以利用UIResponder的nextResponder()方法返回该视图的控制器,以下是官方文档对该方法的描述:
The UIResponder class does not store or set the next responder automatically, instead returningnil by default. Subclasses must override
this method to set the next responder.UIView implements this method by returning theUIViewController
object that manages it (if it has one) or its superview (if it doesn’t);UIViewController
implements the method by returning its view’s superview;UIWindow returns the application object, andUIApplication returns
nil.
因为我要经常用到该方法,所以我直接扩展到UIView里面去了:
The UIResponder class does not store or set the next responder automatically, instead returningnil by default. Subclasses must override
this method to set the next responder.UIView implements this method by returning theUIViewController
object that manages it (if it has one) or its superview (if it doesn’t);UIViewController
implements the method by returning its view’s superview;UIWindow returns the application object, andUIApplication returns
nil.
因为我要经常用到该方法,所以我直接扩展到UIView里面去了:
extension UIView { func parentViewController() -> UIViewController? { for (var next = self.superview; next != nil; next = next?.superview) { let ctr = next?.nextResponder() if (ctr is UIViewController) { return ctr as? UIViewController } } return nil } }
相关文章推荐
- Swift开发第十二篇——protocol组合&static和class
- iOS响应式编程:ReactiveCocoa vs RxSwift 选谁好
- Swift默认参数 & 可变参数
- Swift中UITableView的初步认识
- 35. Quartz 2D初探
- 如何为Swift进行宏定义
- Swift --- 面向对象中类和对象的属性
- swift学习笔记之自定义UITableViewCell
- swift图片浏览器
- swift系统学习控件篇:UIProgressView+NSTimer+UIstepper+UIAlertController
- iOS开发Swift篇(01) 变量&常量&元组
- swift之向ftp服务器传文件
- swift调用相机
- Swift 中的SDWebImage类似库Kingfisher
- swift3 截取字符串(substringwithrange)报错,it will be removed in Swift 3. Use the '..<' operator.
- Swift 与OC之桥接文件
- Swift2.2新特性
- Swift开发第十一篇——Designated、Convenience和Required
- Swift学习资源
- Swift 语言指南( Swift 语言主流学习资源)