Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Swift initializer methods with multiple param in Objective-C

I have One Initializer method in my Swift file like below:

public init(frame: CGRect, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil) {
        self.type = type ?? NVActivityIndicatorView.DEFAULT_TYPE
        self.color = color ?? NVActivityIndicatorView.DEFAULT_COLOR
        self.padding = padding ?? NVActivityIndicatorView.DEFAULT_PADDING
        super.init(frame: frame)
        isHidden = true
}

I want to call this method from my Objective-C file but it's throwing error while compiling.

Error:

/Users/Desktop/old data/ChatScreenViewController.m:396:92: No visible @interface for 'NVActivityIndicatorView' declares the selector 'initWithFrame:type:color:padding:'

Obj-C calling code:

NVActivityIndicatorView *objNVActivityIndicatorView = [[NVActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 100, 100) type:NVActivityIndicatorTypeLineScalePulseOut color:[UIColor blueColor] padding:10]

What I tried:

Added @objc in my Swift class

@objc public final class NVActivityIndicatorView: UIView

Still can't able to access the above method.

My Swift file: NVActivityIndicatorView.swift

What's going wrong?

like image 307
CodeChanger Avatar asked Sep 25 '17 07:09

CodeChanger


2 Answers

To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.

And also this answer.

This apple doc will also help you understand.

So the options for you is to either inherit the class of yours from some Objective C class (In this case compiler adds @objc) or add @objc yourself to your class.

You also need to add to your Objective C class-

#import "<#ProjectName#>-Swift.h"

Real solution to this specific question

Please look at this question, you will get your solution yourself. :)

That question says that optional parameters can't be exposed from Swift to Objective C as all parmeters become _Nonnull.

So I think you will need to create another initializer without optionals and default parameters.

like image 67
Nikhil Manapure Avatar answered Oct 13 '22 00:10

Nikhil Manapure


  1. Try to add @objc also to the function:

    @objc public init(frame: CGRect, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil) {

  2. You need to create a Bridging Header. See https://medium.com/ios-os-x-development/swift-and-objective-c-interoperability-2add8e6d6887

like image 42
Roee84 Avatar answered Oct 12 '22 23:10

Roee84