iOS开发系列-空白页面的友好提示之UITableView

前言

iOS开发过程中,我们最常用的UI控件应该是UITableView了, 它的用途当然就是用来显示一个列表的数据。那么问题来了,当这个列表的数据为空是怎么办?当然最简单的方式就是不用管它,直接就是一个空白页,作为程序员, 一般觉得这不是问题。可是你过的了你家产品经理那关吗?其实作为一个有用户思维的程序员,也应该多关注用户体验。今天我就把我自己实现的空白页面的友好提示功能和大家分享下。

GitHub Demo地址

APP 截图

iOS开发系列-空白页面的友好提示之UITableView_第1张图片
空白页

下面简单介绍下实现原理

  1. 创建一个自定义UITableViewCell来显示空白页,我这里叫EmptyInfoTableViewCell
  2. 在你的ViewController里面的ViewDidLoad方法中注册你的EmptyInfoTableViewCell
tableView.register(UINib(nibName: "EmptyInfoTableViewCell", bundle: nil), forCellReuseIdentifier: "EmptyInfoTableViewCell")
  1. 实现UITableViewDataSource和UITableViewDelegate
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let products = self.products, products.count > 0 else {
            return 1
        }
        return products.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let products = self.products, products.count > 0 else {
            tableView.separatorStyle = .none
            return emptyInfoCellForRowAtIndexPath(indexPath: indexPath)
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell", for: indexPath)

        tableView.separatorStyle = .singleLine

        let product = products[indexPath.row]
        
        cell.textLabel?.text = product
        
        return cell
    }

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        guard let products = self.products, products.count > 0 else {
            return false
        }
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        guard let products = self.products, products.count > 0 else {
            return
        }
        if editingStyle == .delete {
            self.products?.remove(at: indexPath.row)
            tableView.reloadData()
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let products = self.products, products.count > 0 else {
            return tableView.bounds.size.height
        }
        return super.tableView(tableView, heightForRowAt: indexPath)
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let products = self.products, products.count > 0 else {
            return
        }
        
        let productAtIndexPath = products[indexPath.row]
        
        // do what you want
    }
  1. 实现你的空白页里面的Action的代理方法
extension AppleProductsTableViewController: EmptyInfoTableViewCellDelegate {
      func emptyInfoTableViewCellDidTapInfoButton(cell: EmptyInfoTableViewCell) {
        print("Tapped Create Apple Product Now Button")
      }
}

GitHub Demo地址

你可能感兴趣的:(iOS开发系列-空白页面的友好提示之UITableView)