在Swift中使用Objective-C类时“找不到初始化器”

时间:2022-09-07 07:54:08

First time creating a swift app and it was going well until I ran into an issue when trying to use an Objective-C class into the Swift ViewController.

第一次创建一个swift应用时,它运行得很好,直到我在尝试在swift ViewController中使用Objective-C类时遇到了一个问题。

Objective-C Class Init (RKDropdownAlert.h)

objective - c类的Init(RKDropdownAlert.h)

+(void)title:(NSString*)title message:(NSString*)message backgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor time:(NSInteger)seconds;

My attempt:

我的尝试:

var alert: RKDropdownAlert = RKDropdownAlert(title:"Error", message:"Please enter valid credentials.", backgroundColor:UIColor.redColor(), textColor:UIColor.whiteColor(), time:3)

Error: Cannot Find Initializer

错误:无法找到初始化器

How I've previously used the class in Objective C:

我如何在Objective C中使用这个类:

[RKDropdownAlert title:@"Error: Invalid Characters!" message:@"Please remove special characters from the field." backgroundColor:[UIColor redColor] textColor:[UIColor whiteColor] time:3];

I've been looking at this for over a hour now. Can anyone lend a hand? Thanks!

我看这个已经有一个多小时了。谁能帮忙吗?谢谢!

1 个解决方案

#1


2  

As this is a class method and not an initializer, you have to call it with

因为这是一个类方法而不是初始化器,所以您必须使用它来调用它

RKDropdownAlert.title(title:NSString, message:NSString, ...)

if you want to make the method an initializer, you have to change the method declaration in the Objective-C file to

如果要使方法成为初始化器,必须将Objective-C文件中的方法声明更改为

-(instancetype)initWithTitle:(NSString*)title message:(NSString*)message backgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor time:(NSInteger)seconds;

and in the implementation:

和实现:

-(instancetype)initWithTitle:(NSString*)title message:(NSString*)message backgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor time:(NSInteger)seconds
{
    self = [super init];
    if (self) {
        //Create your alert here
    }
    return self;
}

#1


2  

As this is a class method and not an initializer, you have to call it with

因为这是一个类方法而不是初始化器,所以您必须使用它来调用它

RKDropdownAlert.title(title:NSString, message:NSString, ...)

if you want to make the method an initializer, you have to change the method declaration in the Objective-C file to

如果要使方法成为初始化器,必须将Objective-C文件中的方法声明更改为

-(instancetype)initWithTitle:(NSString*)title message:(NSString*)message backgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor time:(NSInteger)seconds;

and in the implementation:

和实现:

-(instancetype)initWithTitle:(NSString*)title message:(NSString*)message backgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor time:(NSInteger)seconds
{
    self = [super init];
    if (self) {
        //Create your alert here
    }
    return self;
}