继承UIView实现自定义可视化组件

import UIKit
//声明在外部可以再其他类调用
enum storeType {
    case common
    case best
}
protocol StoreViewprotocol {
    func changeScore(scorevalue:Int)
}
class StoreView: UIView,StoreViewprotocol {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    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)"
        }
    }
    
    //声明一个初始化方法,根据不同的type
    init(stype:storeType) {
        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) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //实现协议方法
    func changeScore(scorevalue:Int)  {
        score = scorevalue
    }
    
    

}
import UIKit

class ViewController: UIViewController {

    var store1:StoreView?
    var store2:StoreView?
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        makeLabels()
    }
    func makeLabels()
    {
        store1 = StoreView(stype: .common)
        store1?.frame.origin = CGPoint(x:50, y:80)
        store1?.changeScore(scorevalue: 3)
        self.view.addSubview(store1!)
        
        
        store2 = StoreView(stype: .best)
        store2?.frame.origin.x = 170
        store2?.frame.origin.y = 80
        store2?.changeScore(scorevalue: 99)
        self.view.addSubview(store2!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

你可能感兴趣的:(继承UIView实现自定义可视化组件)