swift学习第十六天:懒加载和tableView

懒加载

懒加载的介绍

  • swift中也有懒加载的方式
    • (苹果的设计思想:希望所有的对象在使用时才真正加载到内存中)
  • 和OC不同的是swift有专门的关键字来实现懒加载
  • lazy关键字可以用于定义某一个属性懒加载

懒加载的使用

  • 格式
lazy var 变量: 类型 = { 创建变量代码 }()
  • 懒加载的使用
    // 懒加载的本质是,在第一次使用的时候执行闭包,将闭包的返回值赋值给属性
    // lazy的作用是只会赋值一次
    lazy var array : [String] = {
        () -> [String] in
        return ["why", "lmj", "lnj"]
    }()


import UIKit

class ViewController: UIViewController {
    
    lazy var names : [String] = {
        
        print("------")
        
        return ["why", "yz", "lmj"]
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        _ = names.count
        _ = names.count
        _ = names.count
        _ = names.count
        _ = names.count
        _ = names.count
    }
}
import UIKit

class ViewController: UIViewController {
    
    // MARK:- 懒加载的属性
    /// tableView的属性
    lazy var tableView : UITableView = UITableView()
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
}

// MARK:- 设置UI界面相关
extension ViewController {
    /// 设置UI界面
    func setupUI() {
        // 0.将tableView添加到控制器的View中
        view.addSubview(tableView)
        
        // 1.设置tableView的frame
        tableView.frame = view.bounds
        
        // 2.设置数据源
        tableView.dataSource = self
        
        // 3.设置代理
        tableView.delegate = self
    }
}


// MARK:- tableView的数据源和代理方法:1:设置代理多个代理用,隔开 2:相当于oc的#pragma:// MARK:-  2:若是没有介词,则用下划线来表示:_ tableView

// extension类似OC的category,也是只能扩充方法,不能扩充属性
extension ViewController : UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 1.创建cell:
        let CellID = "CellID"
        var cell = tableView.dequeueReusableCell(withIdentifier: CellID)
        
        if cell == nil {
            // 在swift中使用枚举: 1> 枚举类型.具体的类型 2> .具体的类型
            cell = UITableViewCell(style: .default, reuseIdentifier: CellID)
        }
        
        // 2.给cell设置数据:cell为可选类型,从缓存池中取出的cell可为空,所以为可选类型,最后返回cell的时候要进行强制解包,此时已经保证了可选类型不为空,若为空强制解包会为空
        cell?.textLabel?.text = "测试数据:((indexPath as NSIndexPath).row)"
        
        // 3.返回cell
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击了:((indexPath as NSIndexPath).row)")
    }
}
原文地址:https://www.cnblogs.com/cqb-learner/p/5887226.html