【问题标题】:"Cannot Find Initializer" when using Objective-C class in Swift在 Swift 中使用 Objective-C 类时“找不到初始化程序”
【发布时间】:2015-07-29 01:43:21
【问题描述】:

第一次创建一个 swift 应用程序,它进展顺利,直到我尝试在 Swift ViewController 中使用 Objective-C 类时遇到问题。

Objective-C 类初始化 (RKDropdownAlert.h)

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

我的尝试:

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

错误:找不到初始化程序

我之前在 Objective C 中是如何使用这个类的:

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

我已经看了一个多小时了。任何人都可以伸出援助之手吗?谢谢!

【问题讨论】:

    标签: ios swift


    【解决方案1】:

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

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

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

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

    在实现中:

    -(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;
    }
    

    【讨论】:

    • 类方法应该没问题,只要名称遵循正确的模式,即+alertWithTitle:message:...
    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多