在iOS开发中,如果创建一个自定义的组件通常可以通过继承UIView来实现。下面以一个记分牌组件为例,演示了组件的创建和使用,以及枚举、协议等相关知识的学习。
组件使用:
31
效果图如下:
组件代码:scoreView.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
|
import
UIKit
enum
scoreType
{
case
Common
//普通分数面板
Best
//最高分面板
}
protocol
scoreViewProtocol
{
func
changescore(value s:
Int
)
}
class
scoreView
:
UIView
,
scoreViewProtocol
{
var
label:
UILabel
!
let
defaultFrame =
CGRectMake
(0,100,30)
stype:
String
!
//显示”最高分“还是”分数“
score:
= 0{
didSet
{
//分数变化,标签内容也要变化
label.text =
"\(stype):\(score)"
}
}
//传入分数面板的类型,用于控制标签的显示
init
(stype:
)
{
label =
(frame:defaultFrame)
label.textAlignment =
NSTextAlignment
.
Center
super
.
(frame:defaultFrame)
self
.stype = (stype ==
Common
?
"分数"
:
"最高分"
)
backgroundColor =
UIColor
.orangeColor()
label.font =
UIFont
(name:
"微软雅黑"
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,size:16)
label.textColor =
.whiteColor()
.addSubview(label)
}
required
?(coder aDecoder:
NSCoder
) {
(coder: aDecoder)
}
//实现协议中的方法
)
{
score = s
}
}
|
组件使用:
ViewController
UIViewController
score:
!
bestscore:
!
override
viewDidLoad() {
.viewDidLoad()
setupscoreLabels();
}
setupscoreLabels()
{
score =
)
score.frame.origin =
CGPointMake
(50,80)
score.changescore(value: 0)
.view.addSubview(score)
bestscore =
Best
)
bestscore.frame.origin.x = 170
bestscore.frame.origin.y = 80
bestscore.changescore(value: 99)
.view.addSubview(bestscore)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
|