为了做到数据与视图的分离,我们一般会将一个页面的局部视图以自定义UIView的方式独立出来,如果在该视图中有触发事件(事件处理不需要父视图的上下文),就会遇到在UIView中获取UIViewController的情况,下面是具体实现方法。
#pragma mark - 获取当前view的viewcontroller
+ (UIViewController *)getCurrentViewController:(UIView ) currentView
{
for (UIView next = [currentView superview]; next; next = next.superview)
{
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
{
return (UIViewController *)nextResponder;
}
}
return nil;
}
UINavigationController有个Property,是一个存储所有push进navigationcontroller的视图的集合,是一个栈结构,当我们要POP到某个ViewController的时候,直接用for in 去遍历viewControllers即可。
<pre><code> @property(nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers; // The current view controller stack.</code></pre>
<pre>for (UIViewController *viewController in self.navigationController.viewControllers)
{
if ([viewController isKindOfClass:[AccountManageViewController class]])
{
[self.navigationController popToViewController:viewController animated:YES];
}
}
网友评论