Swift中的懒加载

2018-01-31  本文已影响18人  等不来的期待

在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)

上一篇 下一篇

猜你喜欢

热点阅读