Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a Swift based ViewController from Objective C class's button action

Note: It is not a duplicate one to any question. I could not find any question with some action method and creating an instance for a swift based view controller.

I am calling a swift based view controller in objective c class .m file.

In my ViewController.m I have imported bridge header

#import "ViewController.h"
#import "Project-Bridging-Header.h"

I want to call Swift based view controller from the below action

- (IBAction)tappedButnGo:(UIButton *)sender {

     SwiftViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SwiftViewController"];
}

Here I am getting an error

use of undeclared identifier SwiftViewController

and below is swift class

import UIKit

@objc class SwiftViewController: UIViewController {
 //so on

and my BridgingHeader is empty.

Can anyone help me on loading SwiftViewController when I click on Objective C's button action?

like image 299
Santo Avatar asked Dec 15 '22 05:12

Santo


2 Answers

You need to import following statement in your Controller.h file

#import "ProductModuleName-swift.h"

Here PrductModuleName is your project name

Hope this will help you

like image 179
Nirav D Avatar answered Dec 28 '22 22:12

Nirav D


Check the storyboard SwiftViewController identifier like following image you need to set StoryBoard ID of your SwiftViewController from identiry Inspector :

Following is a steps to use swift class in objective c project:

  • Create New project and select Objective C language.
  • After that when you create new class at that time you get the popup like:

enter image description here

  • Create Bridge header and then go to the build setting and search with Defines Module and make its value YES

  • Now you need to create your swiftVeiwControllers identifire like following code and go to the first viewcontroller

    enter image description here

  • Now you need to import #import "obj_swift-Swift.h". here obj_swift is your project name so its look like #import "yourprojectname-Swift.h"


That's it now you just need to do code like following:

- (IBAction)PushSwift:(id)sender {

     SwiftViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SwiftViewController"];

    [self.navigationController pushViewController:vc animated:YES];
} 

Here is the sample demo code:

https://github.com/nitingohel/obj_swift

like image 35
Nitin Gohel Avatar answered Dec 28 '22 23:12

Nitin Gohel