在Swift项目中,我们可以导入任意用Objective-C写的框架,代码库等。下面以Swift调用Objective-C编写的颜色选择器KKColorListPicker为例。
效果图如下:
实现步骤:
1,首先在项目里导入KKColorListPicker的源码(整个文件夹,在项目上有键“Add Files To XXX”).
2,手工创建桥接头文件bridge.h来包含需要引用的Objective-C头文件,内容如下:
1
2
3
|
//KKColorsSchemeType.h已经包含在KKColorListViewController.h #import "KKColorListViewController.h" #import "KKColor.h" |
3,选择项目,在Build Setting -> Swift Compiler-Code generation -> Objective-C Bridging Header设置里添加bridge.h,如下图所示:
4,页面使用 ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import UIKit class ViewController : UIViewController , KKColorListViewControllerDelegate { //Object-C编写的颜色选择器视图 var viewColor: KKColorListViewController ! override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //初始化颜色选择面板 //这个颜色选择面板是用OC开发,我们导入头文件后就能在Swift里调用了 viewColor = KKColorListViewController (schemeType: KKColorsSchemeType . Crayola ) //此类实现了颜色选择面板的代理协议,并重载了选择颜色和关闭2个回调函数 viewColor.delegate = self //创建一个按钮 var button: UIButton = UIButton .buttonWithType( UIButtonType . System ) as ! UIButton ; //设置按钮位置和大小 button.frame= CGRectMake (10, 50, 100, 30); //设置按钮文字 button.setTitle( "选择背景色" , forState: UIControlState . Normal ) button.addTarget( self ,action: Selector ( "selColor:" ),forControlEvents: UIControlEvents . TouchUpInside ) self .view.addSubview(button); } //点击选择背景色的事件操作 func selColor(sender: AnyObject ) { //显示颜色选择面板 self .presentViewController(viewColor, animated: true , completion: nil ) } //选择颜色后回调 func colorListController(controller: KKColorListViewController , didSelectColor color: KKColor ) { //关闭颜色选择器视图 viewColor.dismissViewControllerAnimated( true , completion: nil ) //设置当前视图的背景颜色为用户选择的颜色 self .view.backgroundColor = color.uiColor() } //用户在颜色选择器视图里点击了关闭 func colorListPickerDidComplete(controller: KKColorListViewController ) { //只需要关闭颜色选择器视图 viewColor.dismissViewControllerAnimated( true , completion: nil ) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } |
源码下载:Test6.zip