由于只是个Demo,所以用的是最简单的Cell来演示,这个界面,包括假数据, 只需要50行代码,非常简洁。实际上在项目中的用法是差不多的,只是需要根据UI的设计,自定义Cell而已。先看效果:

首先先在storyboard上面拖好界面,主要是两个tableView的位置放好,底下的购买按钮是凑数的。

把两个tableView拉到viewController里面

这里需要用到一个我自己封装的轻量级的TableViewManager框架,不需要实现tableView的代理方法,不然两个tableView的代理方法在一起处理,会让ViewController很臃肿。
剩下的代码:
class ViewController: UIViewController {
/// 左侧分类的tableView
@IBOutlet weak var categoryTableView: UITableView!
/// 右侧商品的tableview
@IBOutlet weak var productTableView: UITableView!
var categoryManager: ZJTableViewManager!
var productManager: ZJTableViewManager!
override func viewDidLoad() {
super.viewDidLoad()
//初始化tableviewManager
self.categoryManager = ZJTableViewManager(tableView: self.categoryTableView)
self.productManager = ZJTableViewManager(tableView: self.productTableView)
//假数据
let arrCategory = ["分类1","分类2","分类3","分类4","分类5","分类6"]
let arrProduct = ["面包", "蛋糕", "香蕉", "牛奶", "饼干", "猫粮"]
//添加左边TableView的分类数据
let categorySection = ZJTableViewSection()
self.categoryManager?.add(section: categorySection)
for category in arrCategory {
let categoryItem = ZJTableViewItem(title: category)
categoryItem.isSelectionAnimate = false
categorySection.add(item: categoryItem)
//分类的点击事件,商品滑动到指定分类
categoryItem.setSelectionHandler(selectHandler: {[weak self] (item) in
self?.productManager.tableView.scrollToRow(at: IndexPath(row: 0, section: item.indexPath.row), at: .top, animated: false)
})
}
//添加右边TableView的商品数据
for category in arrCategory {
//添加分区标题
let sectionHeader = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
sectionHeader.text = category
sectionHeader.backgroundColor = UIColor.red
let section = ZJTableViewSection(headerView: sectionHeader)
self.productManager.add(section: section)
//商品列表滑动时header出现的回调与分类列表联动
section.setHeaderWillDisplayHandler({[weak self] (currentSection) in
self?.categoryManager.tableView.selectRow(at: IndexPath(item: currentSection.index, section: 0), animated: false, scrollPosition: .middle)
})
//添加商品
for product in arrProduct {
let item = ZJTableViewItem(title: product)
item.cellHeight = 90
section.add(item: item)
}
}
}
这就是全部的代码了,这里各个事件的触发和调用都很清晰,应该还是比较好理解的。如果需要做三级联动的话也是一样的思路,也很简单。Demo我放到TableViewManager的Demo2里面,感兴趣的话可以去看看,顺便帮忙star一下哈:)
网友评论