简体   繁体   中英

isKindOfClass method to check Swift ViewController in Objective C

There's this AViewController which is written in Swift. Now in my Obj C manager class I want to check the type of the viewcontroller. But it doesn't read because Obj C read the class name as "ProjectName.AViewController". How can we have the below mentioned check?

//Swift class
class AViewController: UIViewController {
}

//Obj C - Manager class
- (void)sampleMethod:(UIViewController *)viewController {
 if ([viewController isKindOfClass:[AViewController class]]) {
  //Action
 }
}

Add @objc(...Name...) before the class name in Swift.

Eg: Swift

//Swift class
@objc(SwiftAViewController)
class AViewController: UIViewController {
}

Eg: ObjC

//Obj C - Manager class
- (void)sampleMethod:(UIViewController *)viewController {
 if ([viewController isKindOfClass:[SwiftAViewController class]]) {
  //Action
 }
}

More details: Name of Swift class when exposed to Objective-C code does not respect the @objc renaming

Because of the bug in swift, @Freerunnering answer will not work. As a work around, we can get the class name as string and then do the string match.

if ([NSStringFromClass([AViewController class] isEqualToString:@"ProjectName.AViewController"]) {

}

let arrControllers = self.navigationController.viewControllers

                    for (indx, vc) in (arrControllers?.enumerated())! {
                        if vc is YourViewController{
                            self.navigationController.viewControllers.remove(at: indx)
                        }
                    }

you can use below code:

for viewController in viewControllers {
                            if viewController.isKind(of: OurViewController.self){
                                print("yes it is OurViewController")
                                self.navigationController?.popToViewController(viewController, animated: true)
                            }
                        }

for more detail you can refer this answer already answered question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM