gpt4 book ai didi

ios - 给定一个 View ,我如何获得它的 viewController?

转载 作者:IT王子 更新时间:2023-10-29 07:28:11 26 4
gpt4 key购买 nike

我有一个指向 UIView 的指针。如何访问它的 UIViewController[self superview] 是另一个 UIView,但不是 UIViewController,对吧?

最佳答案

来自 nextResponderUIResponder 文档:

The UIResponder class does not store or set the next responder automatically, instead returning nil by default. Subclasses must override this method to set the next responder. UIView implements this method by returning the UIViewController 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, and UIApplication returns nil.

因此,如果您递归 View 的 nextResponder 直到它的类型为 UIViewController,那么您就有了任何 View 的父 viewController。

请注意,它仍然可能有一个父 View Controller 。但前提是 View 不属于 viewController 的 View 的 View 层次结构。

Swift 3 和 Swift 4.1 扩展:

extension UIView {
var parentViewController: UIViewController? {
// Starts from next (As we know self is not a UIViewController).
var parentResponder: UIResponder? = self.next
while parentResponder != nil {
if let viewController = parentResponder as? UIViewController {
return viewController
}
parentResponder = parentResponder?.next
}
return nil
}
}

Swift 2 扩展:

extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self.nextResponder()
while parentResponder != nil {
if let viewController = parentResponder as? UIViewController {
return viewController
}
parentResponder = parentResponder!.nextResponder()
}
return nil
}
}

Objective-C 类别:

@interface UIView (mxcl)
- (UIViewController *)parentViewController;
@end

@implementation UIView (mxcl)
- (UIViewController *)parentViewController {
UIResponder *responder = [self nextResponder];
while (responder != nil) {
if ([responder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)responder;
}
responder = [responder nextResponder];
}
return nil;
}
@end

这个宏避免了类别污染:

#define UIViewParentController(__view) ({ \
UIResponder *__responder = __view; \
while ([__responder isKindOfClass:[UIView class]]) \
__responder = [__responder nextResponder]; \
(UIViewController *)__responder; \
})

关于ios - 给定一个 View ,我如何获得它的 viewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1372977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com