gpt4 book ai didi

ios - 如何让这个UINavigationController求代码更优雅?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:08:11 24 4
gpt4 key购买 nike

-(UINavigationController *) navigationControllerOfParentOrSelf //These 2 functions are short so I just go ahead
{
UIViewController * current=self;
while (current) {
UINavigationController * nav = current.navigationController;
if (nav) {
return nav;
}
current=current.parentViewController;
}
return nil;
}

-(UITabBarController *) tabBarControllerOfParentOrSelf
{
UIViewController * current=self;
while (current) {
UITabBarController * tc = current.tabBarController;
if (tc) {
return tc;
}
current=current.parentViewController;
}
return nil;
}

看起来有很多重复的代码。

基本上我只想知道 UIViewController 是否在 UINavigationController 中。问题是当 UIViewController 是 childViewController 时,navigationController 属性通常为 nil

最佳答案

我会建议这样的事情:

-(UINavigationController *) navigationControllerOfParentOrSelf
{
return [self parrentControllerOfParrentOrSelfWithGetter: @selector(navigationController)];
}

-(UITabBarController *) tabBarControllerOfParentOrSelf
{
return [self parrentControllerOfParrentOrSelfWithGetter: @selector(tabBarController)];

}

- (id) parrentControllerOfParrentOrSelfWithGetter: (SEL) getter
{
UIViewController * current=self;
while (current) {
id res = [current performSelector: getter];
if (res) {
return tc;
}
current=current.parentViewController;
}
return nil;
}

关于ios - 如何让这个UINavigationController求代码更优雅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377286/

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