In iOS development, if you create a custom component, you can usually implement it by inheriting UIView. The following is an example of a scoreboard component that demonstrates the creation and use of components, as well as learning about enumerations, protocols, and other related knowledge.as follows:Component code: Scoreview.swift
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
import UIKit
enum ScoreType
{
case Common
//普通分数面板
case Best
//最高分面板
}
protocol ScoreViewProtocol
{
func changeScore(value s:
Int
)
}
class ScoreView
:
UIView
,
ScoreViewProtocol
{
var label:
UILabel
!
let defaultFrame =
CGRectMake
(0,0,100,30)
var stype:
String
!
//显示”最高分“还是”分数“
var score:
Int = 0{
didSet
{
//分数变化,标签内容也要变化
label.text =
"\(stype):\(score)"
}
}
//传入分数面板的类型,用于控制标签的显示
init
(stype:
ScoreType
)
{
label =
UILabel
(frame:defaultFrame)
label.textAlignment =
NSTextAlignment
.
Center
super
.
init
(frame:defaultFrame)
self
.stype = (stype ==
ScoreType
.
Common ?
"分数"
:
"最高分"
)
backgroundColor =
UIColor
.orangeColor()
label.font =
UIFont
(name:
"微软雅黑"
, size:16)
label.textColor =
UIColor
.whiteColor()
self
.addSubview(label)
}
required init
(coder aDecoder:
NSCoder
) {
super
.
init
(coder: aDecoder)
}
//实现协议中的方法
func changeScore(value s:
Int
)
{
score = s
}
}
|
Component use:
12345678910111213141516171819202122232425262728293031323334 |
import UIKit
class ViewController
:
UIViewController {
var score:
ScoreView
!
var bestscore:
ScoreView
!
override func viewDidLoad() {
super
.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupScoreLabels();
}
func setupScoreLabels()
{
score =
ScoreView
(stype:
ScoreType
.
Common
)
score.frame.origin =
CGPointMake
(50, 80)
score.changeScore(value: 0)
self
.view.addSubview(score)
bestscore =
ScoreView
(stype:
ScoreType
.
Best
)
bestscore.frame.origin.x = 170
bestscore.frame.origin.y = 80
bestscore.changeScore(value: 99)
self
.view.addSubview(bestscore)
}
override func didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
Swift-Inherit UIView implement custom visualization components (with Scoreboard sample)