TableView section - QDDCoder/LZLearniOS GitHub Wiki
pod 'RxDataSources'

//设置数据绑定的中间件
private var dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String,HomeCategoryModel>> { (_, tableView, indexPath, item) -> UITableViewCell in
let cell = tableView.dequeueReusableCell(withIdentifier: "LZBaseHomeCell", for: indexPath) as! LZBaseHomeCell
cell.nameLabel.text=item.name
cell.backgroundColor = .randomColor
//为cell注册拖拽方法
cell.userInteractionEnabledWhileDragging = true
return cell
}.then {
//设置section的header
$0.titleForHeaderInSection={(dataSourceIn,section) ->String in
return dataSourceIn[section].model
}
//设置section的footer
$0.titleForFooterInSection={(dataSourceIn,section) ->String in
return dataSourceIn[section].model
}
//设置可移动
$0.canMoveRowAtIndexPath={(dataSourceIn,indexPath) -> Bool in
return true
}
//设置可编辑
$0.canEditRowAtIndexPath={(dataSourceIn,indexPath) -> Bool in
if dataSourceIn[indexPath].name == "第一个"{
return true
}
return false
}
}
private var response:BehaviorSubject<[SectionModel<String, HomeCategoryModel>]>?
private var dataModel=[SectionModel(model: "base", items:
[
HomeCategoryModel(withName: "第一个", withJump: UIViewController.self),
HomeCategoryModel(withName: "第二个", withJump: UIViewController.self),
HomeCategoryModel(withName: "第三个", withJump: UIViewController.self),
]),
SectionModel(model: "base2", items:
[
HomeCategoryModel(withName: "第一个", withJump: UIViewController.self),
HomeCategoryModel(withName: "第二个", withJump: UIViewController.self),
HomeCategoryModel(withName: "第三个", withJump: UIViewController.self),
])]
//创造数据
response = BehaviorSubject(value:dataModel)
//绑定数据
response!.asObserver().bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)
tableView.rx.itemSelected.map {[weak self] (indexPath) in
return (indexPath,self!.dataSource[indexPath])
}.subscribe(onNext:{(index,model) in
ToastView.instance.showToast(content: "点击了===>>>\(index.section)===>>>\(model.name)")
}).disposed(by: disposeBag)
// cell 拖动
extension LZRXSwiftTableSectionView:UITableViewDropDelegate
{
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
}
func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
// cell的动画执行完毕后 执行一次数据交换
func tableView(_ tableView: UITableView, dropSessionDidEnd session: UIDropSession) {
dataModel = dataSource.sectionModels
response?.onNext(dataModel)
}
}
注意点
-
在拖动过程中数据data的修改只是修改了
RxTableViewSectionedReloadDataSource
中的数据,所以在func tableView(_ tableView: UITableView, dropSessionDidEnd session: UIDropSession)
move动画执行完后进行一次数据重新设置。为了解决此时对cell执行增删操作数据不一致. -
不行,因为
RxTableViewSectionedReloadDataSource
只是起到了中间件的作用。和dataModel
中的数据不一致,并且RxTableViewSectionedReloadDataSource
中的section是只读的。