Swift调用OC
将 Objective-C 导入 Swift
要在同一个 app target 中导入 Objective-C 文件供 Swift 使用,你需要依赖 Objective-C的桥接头文件(Objective-C bridging header)来暴露给 Swift。当你添加 Swift 文件到现有的 Objective-C 应用时,Xcode 会自动创建这些头文件,反之亦然。
我的代码是Swift
点击Create Bridging Header会自动生成一个和你项目名一样的文件
请把你想要在Swift调用的OC的文件import到.h文件中
然后还需要设置文件
Swift中使用oc代码的方式:
let customViewOC = ocCustomShapeImageView.init(frame: CGRectMake(200, 70, 150, 120))
customViewOC.right = CGRectGetWidth(UIScreen.mainScreen().bounds);
customViewOC.top = 120;
customViewOC.image = UIImage.init(named: "image")
self.view.addSubview(customViewOC)
OC代码
@interface ocCustomShapeImageView()
{
CAShapeLayer *_maskLayer;
}
@end
@implementation ocCustomShapeImageView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self PictureShape];
}
return self;
}
//使用图片来遮罩
- (void)PictureShape
{
_maskLayer = [CAShapeLayer layer];
_maskLayer.frame = self.bounds;
_maskLayer.contentsScale = [UIScreen mainScreen].scale;
_maskLayer.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1);
_maskLayer.contents = (id)[UIImage imageNamed:@"communication_chat_right.png"].CGImage;
[self.layer setMask:_maskLayer];
}