Swift - 继承UIView实现自定义可视化组件(附记分牌样例)

时间:2022-06-01 20:36:13
在iOS开发中,如果创建一个自定义的组件通常可以通过继承UIView来实现。下面以一个记分牌组件为例,演示了组件的创建和使用,以及枚举、协议等相关知识的学习。
效果图如下:
  Swift - 继承UIView实现自定义可视化组件(附记分牌样例)
组件代码: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  //普通分数面板
    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
    }
}

组件使用:

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
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.
    }
}