Swift中的懒加载

在OC中写代码时,为了节省内存的占用,我们常常用到懒加载,现在转手写Swift用到懒加载,语法和OC还有些许出入,下面就以UITableView为例介绍下懒加载,看以下代码:

 lazy var tableView: UITableView = {
        
        var tableView = UITableView()
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: -20, width: AppConstants.ScreenWidth, height: AppConstants.ScreenHeight-30), style: UITableViewStyle.grouped)
    
        //遵循tableView的代理
        tableView.delegate = self
        tableView.dataSource = self
        
        //适配ios11
        tableView.sectionFooterHeight = 0
        tableView.sectionHeaderHeight = 0
        
        tableView.tableHeaderView = self.headerView
    
        //自定义cell需要注册,如果用原生的可以不写这一步
        tableView.register(MineCell.classForCoder(), forCellReuseIdentifier: "cell")
        
        return tableView
    }()

在Swift中不用声明控件,直接按照以上懒加载的方法写就行

不过要记得在override func viewDidLoad()方法中把tableView加到父视图中

self.view.addSubview(self.tableView)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。