为什么这些Objective-C和Swift子类的行为有所不同?

时间:2014-07-30 20:50:54

标签: objective-c uibutton swift

我的项目中有以下两个类:

目标C (无头文件)

#import "CircleButton.h"

@implementation CircleButton

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    self.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.layer.borderWidth = 3;
    self.layer.cornerRadius = self.frame.size.width / 2;
    return self;
}

@end

夫特:

import Foundation

class CircleButton : UIButton {
    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
        self.layer.borderColor = UIColor.whiteColor().CGColor
        self.layer.borderWidth = 3
        self.layer.cornerRadius = self.frame.size.width / 2
    }
}

据我所知,它们是相同的,但是当我在Interface Builder中的一系列按钮上使用它们时,Swift实现仅在第一个按钮周围绘制白色圆圈边框。使用Objective C实现时,所有按钮都有圆边框。我需要做什么才能使我的Swift文件像Objective C一样?

更新

我刚注意到我还在日志中收到以下错误消息:

Unknown class CircleButton in Interface Builder file.

这显示N-1次,其中N是我在Storyboard中使用Swift版本文件的次数。

1 个答案:

答案 0 :(得分:4)

在将按钮上的模块更改为不存在的内容后,我能够重现您看到的错误。

因此请确保在IB中正确设置模块。这也解释了为什么obj-c代码在swift失败时有效。