SoFunction
Updated on 2025-04-12

How to get the controller where the current View is located in iOS

Preface

I don’t know if you have ever encountered the carousel images when making carousel images. Some carousel images show advertisements, some activities, etc. and other things. When you click on a carousel, you need to jump to a different controller. The click event is written in the controller. In order to avoid too much controller code and bloated display. I created a UIWindow category, and I'll call itModel (GetCurrentVC)

Implementation method

Google has many methods. The following method is effective for personal testing. If you need it, you can refer to it.

one:

@interfaceUIWindow (GetCurrentVC)

- (UIViewController*)getCurrentVC;

@end

two:

#import"UIWindow+"

@implementationUIWindow (GetCurrentVC)

- (UIViewController*)getCurrentVC {

UIViewController*result =nil;

UIWindow* window = [[UIApplicationsharedApplication]keyWindow];

if(!=UIWindowLevelNormal)

{

NSArray*windows = [[UIApplicationsharedApplication]windows];

for(UIWindow* tmpWininwindows)

{

if(==UIWindowLevelNormal)

{

window = tmpWin;

break;

}

}

}

UIView*frontView = [[windowsubviews]objectAtIndex:0];

idnextResponder = [frontViewnextResponder];

if([nextResponderisKindOfClass:[UIViewControllerclass]])

result = nextResponder;

else

result = ;

returnresult;

}

@end

Summarize

The above is how to obtain the current controller where the View is located in iOS. I hope this article will be of some help to everyone in developing iOS. If you have any questions, you can leave a message to communicate.