在Swift项目中,我们可以导入任意用Objective-C写的框架,代码库等。下面以Swift调用Objective-C编写的颜色选择器KKColorListPicker为例。
效果图如下:
实现步骤:
1,首先在项目里导入KKColorListPicker的源码(整个文件夹,在项目上有键“Add Files To XXX”).
1
2
3
//KKColoRSSchemeType.h已经包含在KKColorListViewController.h
#import
"KKColorListViewController.h"
"KKColor.h"
3,选择项目,在Build Setting -> Swift Compiler-Code generation -> Objective-C Bridging Header设置里添加bridge.h,如下图所示:
4,页面使用ViewController.swift
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.
//初始化颜色选择面板
viewColor.delegate =
self
//创建一个按钮
button:
UIButton
=
(type:
UIButtonType
System
)
;
//设置按钮位置和大小
button.frame=
CGRectMake
(10,50,100,30);
//设置按钮文字
button.setTitle(
"选择背景色"
UIControlState
Normal
)
button.addTarget(
self
Selector
(
"selColor:"
),forControlEvents:
UIControlEvents
TouchUpInside
)
.view.addSubview(button);
}
//点击选择背景色的事件操作
selColor(sender:
AnyObject
) {
//显示颜色选择面板
.presentViewController(viewColor,animated:
true
nil
)
}
//选择颜色后回调
colorListController(controller:
KKColor
)
{
//关闭颜色选择器视图
viewColor.dismissViewControllerAnimated(
)
//设置当前视图的背景颜色为用户选择的颜色
.view.backgroundColor = color.uiColor()
}
colorListPickerDidComplete(controller:
)
{
//只需要关闭颜色选择器视图
)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
1
2
3
|
//KKColoRSSchemeType.h已经包含在KKColorListViewController.h
#import
"KKColorListViewController.h"
"KKColor.h"
|
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.
//初始化颜色选择面板
viewColor.delegate =
self
//创建一个按钮
button:
UIButton
=
(type:
UIButtonType
System
)
;
//设置按钮位置和大小
button.frame=
CGRectMake
(10,50,100,30);
//设置按钮文字
button.setTitle(
"选择背景色"
UIControlState
Normal
)
button.addTarget(
self
Selector
(
"selColor:"
),forControlEvents:
UIControlEvents
TouchUpInside
)
.view.addSubview(button);
}
//点击选择背景色的事件操作
selColor(sender:
AnyObject
) {
//显示颜色选择面板
.presentViewController(viewColor,animated:
true
nil
)
}
//选择颜色后回调
colorListController(controller:
KKColor
)
{
//关闭颜色选择器视图
viewColor.dismissViewControllerAnimated(
)
//设置当前视图的背景颜色为用户选择的颜色
.view.backgroundColor = color.uiColor()
}
colorListPickerDidComplete(controller:
)
{
//只需要关闭颜色选择器视图
)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
|