zoukankan      html  css  js  c++  java
  • swif开发之--协议的使用

    以前在oc构建的项目中,如果这个页面需要构建一些指定的页面,一般我会重新创建个集成与UIView的类,然后同时创建XXX.xib文件,然后直接在上面拖拽控件,非常快速,当然也可以手动布局!个人更喜欢可视化布局!

    在swift下,其实实现的逻辑也是一样的,布局风格也相仿,里面加了一个代理传值,

    具体代码如下:

    1,新建一个集成与UIView的类

    import UIKit
    
    //创建枚举
    enum ScoreType{
        case common //普通分数面板
        case best       //最高分数板
    }
    
    //代理协议的使用
    protocol ScoreViewProtocol{
        func changeScore(value s:Int)
    }
    
    class ScoreView: UIView,ScoreViewProtocol {
    
        var scoreLab:UILabel!
        
        let defaultFrame = CGRect(x:0,y:0,100,height:30)
        var stype:String!
        var score:Int = 0{
            didSet{
                //分数变化,标签内容也要变化
                scoreLab.text = "(String(describing: String(stype))):(score)"
            }
        }
        
        //传入分数面板的类型,用于控制标签的显示
        init (stype:ScoreType)
        {
            scoreLab = UILabel(frame:defaultFrame)
            scoreLab.textAlignment = .center
            super.init(frame:defaultFrame)
            self.stype = (stype == .common ? "我的":"你的")
            
            backgroundColor = UIColor.orange
            scoreLab.font = UIFont(name:"微软雅黑",size:16)
            scoreLab.textColor = UIColor.white
            self.addSubview(scoreLab)
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        //实现协议中的方法
        func changeScore(value s:Int)
        {
            score = s
        }
    
    }

    2,在vc里面具体调用

    var score:ScoreView!
    var bestscore:ScoreView!

    具体实现:

    func initScoreView(){
            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)
        }

    效果如下:

    仅做记录

  • 相关阅读:
    转移阵地啦
    春之感--3月10日
    小鱼儿
    关于时间方法(date和simpledateformat)的实验
    hadoop练习处理地震数据
    出现log4j.properties问题
    远程hadoop集群方法
    小W学物理
    灵知的太阳信仰
    Blue
  • 原文地址:https://www.cnblogs.com/hero11223/p/7607414.html
Copyright © 2011-2022 走看看