美文网首页Swift
swift 中的set方法

swift 中的set方法

作者: 陈藩 | 来源:发表于2018-05-06 22:59 被阅读0次

    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
    
    

    相关文章

      网友评论

        本文标题:swift 中的set方法

        本文链接:https://www.haomeiwen.com/subject/kryprftx.html