需求:
- 左侧为竖立的菜单栏,可滚动,点击可定位到右侧相应的section(自动滚动到sectionHeader);
- 右侧为多section的具体商品列表,可滚动,滚动过程中section触顶时,左侧菜单栏自动选中相应的项;
思路:
- 确定滚动方向;
- 对于右侧,向下滚动时,监听willDisplay cell:,新section出现时触发选中逻辑;
- 对于右侧,向上滚动时,监听didEndDisplaying cell:,老section消失时触发选中逻辑;
- 对于左侧点击事件,直接滚动右侧至相应的section位置即可。
代码逻辑大致如下:
//viewModel.$currentType
// .receive(on: DispatchQueue.main)
// .sink(receiveValue: { [weak self] _ in
// self?.leftTableView.reloadData()
// }).store(in: &cancellables)
extension AIToolsController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
// 自行补齐
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 自行补齐
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 自行补齐
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// 自行补齐
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == leftTableView {
if viewModel.currentType != indexPath.row {
viewModel.currentType = indexPath.row
rightTableScrollTo(indexPath.row, animate: true)
}
} else if tableView == rightTableView {
let toolList = viewModel.toolListArr[indexPath.section]
if let tools = toolList.tools {
let toolItem = tools[indexPath.row]
jumpToDetail(toolItem)
}
} else {
// 其他
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if scrollDirection == .ScrollDirectionDown {
let toolList = viewModel.toolListArr[indexPath.section]
if let tools = toolList.tools {
if indexPath.row == tools.count - 1, indexPath.section < viewModel.toolListArr.count {
viewModel.currentType = indexPath.section
}
}
}
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if scrollDirection == .ScrollDirectionUp {
let toolList = viewModel.toolListArr[indexPath.section]
if let tools = toolList.tools {
if indexPath.row == tools.count - 1, indexPath.section + 1 < viewModel.toolListArr.count {
viewModel.currentType = indexPath.section + 1
}
}
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentContentOffset = scrollView.contentOffset.y
if currentContentOffset > lastContentOffset {
scrollDirection = .ScrollDirectionUp
} else if currentContentOffset < lastContentOffset {
scrollDirection = .ScrollDirectionDown
}
lastContentOffset = currentContentOffset
}
func rightTableScrollTo(_ section: Int, animate: Bool) {
if section < viewModel.typeCount {
let indexPath = IndexPath.init(row: 0, section: section)
rightTableView.scrollToRow(at: indexPath, at: .top, animated: animate)
}
}
}
网友评论