简体   繁体   中英

How to call Objective C viewcontroller in Swift

I found a ViewController SDK using objective C. I want to use it swift but fail to call.

Can you suggest me any idea for using it?

I want to create a storyboard and set the custom class in ViewControllerObjectiveC , but still fail to open the viewcontroller .

let vc = sb.instantiateViewController(withIdentifier: "ViewControllerObjectiveC") as! ViewControllerObjectiveC
self.dismiss(animated: false, completion: nil)
self.presentingViewController?.present(vc, animated: false, completion: nil)

In order to interact Obj-C code with Swift you will need to have a bridging header file. The name of the bridging header MUST be like <YourProject>-Bridging-Header.h . While you can create it manually there is an option which the Xcode creates it yourself. For the second option create a new file with .m extension. The Xcode will ask you to create a bridging header. Approve it.

Now import everything in this file you need to reach from Swift. In your case put the following inside your bridging header:

#import "ViewControllerObjectiveC.h"

Assuming your Obj-C file has the name ViewControllerObjectiveC.h. The code you shared should work now.

Bridging Header is the way to solve your problem.

See this Apple Document:

https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_objective-c_into_swift

Step 1 Drag and drop your Objective-C files into the project after that you will see this message inside your Xcode project.

See this popup

Then click on Create Bridging header option. It will create one header file inside your project.

Confirm Header File

Now you just have to Import your Objective C File into created header file.

That's It.

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