Swift - 继承UIView实现自定义可视化组件(附记分牌样例)
在iOS开发中,如果创建一个自定义的组件通常可以通过继承UIView来实现。下面以一个记分牌组件为例,演示了组件的创建和使用,以及枚举、协议等相关知识的学习。(本文代码已升级至Swift3)
组件使用:
效果图如下:
组件代码:ScoreView.swift
import UIKit enum ScoreType{ case common //普通分数面板 case best //最高分面板 } protocol ScoreViewProtocol{ func changeScore(value s:Int) } class ScoreView:UIView, ScoreViewProtocol { var label:UILabel! let defaultFrame = CGRect(x:0, y:0, width:100, height:30) var stype:String! //显示”最高分“还是”分数“ var score:Int = 0{ didSet{ //分数变化,标签内容也要变化 label.text = "\(stype!):\(score)" } } //传入分数面板的类型,用于控制标签的显示 init(stype:ScoreType) { label = UILabel(frame:defaultFrame) label.textAlignment = .center super.init(frame:defaultFrame) self.stype = (stype == .common ? "分数":"最高分") backgroundColor = UIColor.orange label.font = UIFont(name:"微软雅黑", size:16) label.textColor = UIColor.white self.addSubview(label) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //实现协议中的方法 func changeScore(value s:Int) { score = s } }
组件使用:
import UIKit class ViewController: UIViewController { var score:ScoreView! var bestscore:ScoreView! override func viewDidLoad() { super.viewDidLoad() setupScoreLabels(); } func setupScoreLabels() { score = ScoreView(stype: .common) score.frame.origin = CGPoint(x:50, y:80) score.changeScore(value: 0) self.view.addSubview(score) bestscore = ScoreView(stype: .best) bestscore.frame.origin.x = 170 bestscore.frame.origin.y = 80 bestscore.changeScore(value: 99) self.view.addSubview(bestscore) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
你这代理有什么用?