雖然Swift語言已更新至3.0,但畢竟Objective-C語言已成熟多年,不少好用的第三方框架都是OC編寫的,如AFNetWorking(Swift版本爲Alamofire)等,因此這篇文章給你們介紹如何用Swift語言調用OC編寫的第三方API(本例採用無限輪播圖第三方SDCycleScrollView)swift
SDCycleScrollView用OC語言調用以下:框架
直接將第三方文件拖到項目中,再在須要的類中#import "SDCycleScrollView.h"就可以使用第三方的APIide
//
// 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不一樣,須要額外作一些配置:oop
首先仍是要把第三方文件拖到項目中,接着在項目中建立Swift-Objective-C橋接文件,例如我在項目中建立了一個SwiftSocket-Brigding-Header.h的頭文件,並在文件中引入第三方頭文件(用OC編寫),如圖:ui
接着在項目Targets-Build Settings中搜索swift,找到Objective-C Bridging Header,並將該值設爲上面橋接文件所在路徑(這裏我用的是絕對路徑),如圖:spa
通過以上步驟,就可在Swift文件中用Swift語言調用OC編寫的第三方API,用Swift語言調用SDCycleScrollView第三方以下:blog
//
// 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!)
}
}
效果圖以下:get