swift 中的set方法

swift中set方法的简单实用

以一个简单的UITableViewCell为例子


class ListCell: UITableViewCell {

    var nameLab:UILabel!
    var rssiLab:UILabel!
    
    var name:String?{
        willSet{
            print("将要改变1")
        }
        didSet{
            print("已经改变1")
            self.nameLab.text  = self.name!
        }
    }
    var rssi:String?{
        willSet{
            print("将要改变2")
        }
        
        didSet{
            print("已经改变2")
            self.rssiLab.text = self.rssi!
        }
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier);
        name = nil
        rssi = nil
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    
    func setupUI() {
        nameLab = UILabel.init();
        nameLab.font = UIFont.systemFont(ofSize: 14)
        nameLab.textAlignment = NSTextAlignment.left;
        nameLab.textColor = UIColor.black;
        addSubview(self.nameLab)
        
        rssiLab = UILabel.init();
        rssiLab.font = UIFont.systemFont(ofSize: 13)
        nameLab.textAlignment = NSTextAlignment.center;
        nameLab.textColor = UIColor.black;
        self.addSubview(self.rssiLab)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.nameLab.frame = CGRect.init(x: 20, y: 20, width: 100, height: 28);
        self.rssiLab.frame = CGRect.init(x: 140, y: 20, width: 100, height: 28);
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let reusedID:String = "Cell"
        let cell:ListCell = tableView.dequeueReusableCell(withIdentifier: reusedID) as! ListCell
        
        let peripheral:CBPeripheral = self.datas[indexPath.row] as! CBPeripheral;
//        cell.nameLab.text = peripheral.name
//        cell.rssiLab.text = "-50"
        cell.name = peripheral.name;
        cell.rssi = "-50";
    
        return cell;
    }


打印的结果


将要改变1
已经改变1
将要改变2
已经改变2

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,627评论 4 61
  • 走在那年我们走过的柳树下 泛泛阳光在眼里优雅 开着的花被风羽化 是你的笑容将我停下 如果我是鱼呢 绝不向往蔚蓝的天...
    李译阅读 3,255评论 2 5
  • 第一斧:区分事实一意见,训练自己表达事实而不是意见。 意见表达:今天你又迟到了! 事实表达:今天你迟到了 ,这是本...
    萌妈育儿记阅读 4,134评论 0 2
  • 人生在世悉数相逢,每一个人的出现都是冥冥中安排好的,每一个人的缘分都是命中注定的。崎岖的命运历练了几个年轻人的优秀...
    东极广场阅读 3,964评论 0 0

友情链接更多精彩内容