isKindOfClass方法检查Objective C中的Swift ViewController

时间:2015-04-08 12:50:53

标签: ios objective-c swift

这个AViewController是用Swift编写的。现在在我的Obj C管理器类中,我想检查viewcontroller的类型。但它没有读取,因为Obj C将类名称读为“ProjectName.AViewController”。我们怎样才能进行下面提到的检查?

//Swift class
class AViewController: UIViewController {
}

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

4 个答案:

答案 0 :(得分:0)

在Swift中的类名前添加@objc(...Name...)

例如: 迅速

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

例如:ObjC

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

更多详情:Name of Swift class when exposed to Objective-C code does not respect the @objc renaming

答案 1 :(得分:0)

由于swift中的错误,@ Freeerunner答案将无效。 作为解决方法,我们可以将类名称作为字符串,然后进行字符串匹配。

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

}

答案 2 :(得分:-1)

let arrControllers = self.navigationController.viewControllers

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

答案 3 :(得分:-1)

您可以使用以下代码:

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

有关详细信息,请参阅此答案already answered question