专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构

显示表格数据

  • HMHomeViewController 里定义 微博模型数组 属性

    // MARK: - 属性
    /// 微博模型数组
    var statusVMs: [HMStatusViewModel]? {
      didSet {
          tableView.reloadData()
      }
    }
    
  • 修改 HomeTableViewController 里的 loadStatus 方法

    override func viewDidLoad() {
      super.viewDidLoad()
    
      ...
    
      // 测试加载微博数据
      HMStatusListViewModel.shared.loadStatus { (statusVMs: [HMStatusViewModel]?, error: Error?) in
    
          if error != nil {
              print("加载微博数据出错 error: \(error)")
              return
          }
    
          print("加载到微博数据: \(statusVMs)")
          self.statusVMs = statusVMs
      }
    }
    
  • viewDidLoad 中注册可重用 Cell
    // 注册可重用 cell
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    
  • 实现 tableView 数据源代理方法

    // MARK: - table 数据源和代理方法
    extension HMHomeViewController {
      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          // ? 表示如果statusVMs有值才执行statusVMs.count
          // ?? statusVMs = nil 时返回 0
          return self.statusVMs?.count ?? 0
      }
    
      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    
          // 获取对应的单个微博VM
          let statusVM = self.statusVMs![indexPath.row]
          cell.textLabel?.text = statusVM.status.text
    
          return cell
      }
    }
    
  • 运行: 结果如下

results matching ""

    No results matching ""