在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
虽然Swift语言已更新至3.0,但毕竟Objective-C语言已成熟多年,很多好用的第三方框架都是OC编写的,如AFNetWorking(Swift版本为Alamofire)等,所以这篇文章给大家介绍如何用Swift语言调用OC编写的第三方API(本例采用无限轮播图第三方SDCycleScrollView)
SDCycleScrollView用OC语言调用如下: 直接将第三方文件拖到项目中,再在需要的类中#import "SDCycleScrollView.h"就可使用第三方的API //
// ViewController.swift
// swift demo - swift调用oc无限轮播API
//
// Created by 柯其谱 on 17/3/12.
// Copyright © 2017年 柯其谱. All rights reserved.
//
#import "ViewController.h"
#import "SDCycleScrollView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *images = @[@"h1.jpg",@"h2.jpg",@"h3.jpg",@"h4.jpg"];
/**
* @param frame :SDCycleScrollView 的frame
* @param shouldInfiniteLoop: 是否循环
*/
SDCycleScrollView *scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,180) shouldInfiniteLoop:YES imageNamesGroup:images];
[self.view addSubview:scrollView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
但Swift不同,需要额外做一些配置: 首先还是要把第三方文件拖到项目中,接着在项目中创建Swift-Objective-C桥接文件,例如我在项目中创建了一个SwiftSocket-Brigding-Header.h的头文件,并在文件中引入第三方头文件(用OC编写),如图:
接着在项目Targets-Build Settings中搜索swift,找到Objective-C Bridging Header,并将该值设为上面桥接文件所在路径(这里我用的是绝对路径),如图:
经过以上步骤,就可在Swift文件中用Swift语言调用OC编写的第三方API,用Swift语言调用SDCycleScrollView第三方如下:
//
// ViewController.swift
// swift demo - swift调用oc无限轮播API
//
// Created by 柯其谱 on 17/3/12.
// Copyright © 2017年 柯其谱. All rights reserved.
//
import UIKit
//MARK: View life cycle
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupSubviews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: Setup
extension ViewController {
fileprivate func setupSubviews() -> Void {
let imageNames = ["h1.jpg", "h2.jpg", "h3.jpg", "h4.jpg"]
let cycleScrollView = SDCycleScrollView.init(frame: CGRect (x: 0, y: 0, width: self.view.frame.size.width, height: 200), shouldInfiniteLoop: true, imageNamesGroup: imageNames)
self.view.addSubview(cycleScrollView!)
}
}
效果图如下:
|
请发表评论