Search code examples
iosobjective-cswiftinitializer

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?


Solution

  • 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.