11

I have an Objective-C project, and need hints on how to call a ViewController which is in Swift from another controller in Objective-C?

jvarela
  • 3,153
  • 1
  • 19
  • 38
rimtej
  • 157
  • 1
  • 1
  • 9

2 Answers2

18

Apparently it's quite easy.

  1. You have to first make sure you're prepending your class declaration with @objc so that it's available to your Objective-C ones.

For example:

import Foundation

// Belongs to target 'TestProject'
@objc class SwiftController: UIViewController {

    //... truncated

}
  1. Now you simply have to import the name of your target (that the swift controller belongs to), appended with '-Swift.h'—exposing its interface—like so:

    #import "TestProject-Swift.h"

dangnabit
  • 589
  • 2
  • 9
  • 1
    no result, when i import a class #import "TestClass-Swift.h" doesen't find that class – rimtej Aug 25 '15 at 11:58
  • 1
    You need to go in to your build settings and set the `Objective-c Generated Interface Header.` – rckoenes Aug 25 '15 at 12:40
  • @rckoenes doesen't work yet? – rimtej Aug 25 '15 at 13:54
  • 2
    Make sure you're not importing the class and importing the **target** your class is in. So, if your class `TestClass` is in a project named `TestProject` (most likely with an auto-generated target called `TestProject`), then you would need to import `TestProject-Swift.h`. Remember, Swift files don't have headers. – dangnabit Aug 25 '15 at 21:25
-3

Create a new file "YourAppName-Bridging-Header.h" and in this file you have to import "Your objective-C view controller.h"

Go to Build setting and search for bridging header and link with your birdging-header path.

Now you are able to write code in swift as usual.

Sudhir
  • 77
  • 5
  • 3
    I think OP is asking about accessing a Swift controller in an Objective C file. – dangnabit Aug 25 '15 at 10:17
  • 1
    You can use this either you have to use swift controller in objective C file or objective C controller in swift file. – Sudhir Aug 25 '15 at 10:40
  • 1
    Right, I see what you mean. Don't you have to prepend the Swift classes with `@objc`? – dangnabit Aug 25 '15 at 10:43
  • You shouldn't make the header anyway. It is automatically generated with the proper settings. Making it yourself invites a lot of user error. – Abandoned Cart Jul 29 '19 at 19:47