LongPressReorder
LongPressReorder解决了在使用iOS设备上的表格时一个常见的用例:使用长按手势重排表格行,类似于拖放手势。轻量级且易于使用,LongPressReorder适用于任何管理UITableView的视图控制器。支持自动滚动和带有一个或多个部分的表格。
此Swift模块基于在raywenderlich.com上发布的知名文章。
示例
要运行示例项目,请克隆仓库,然后首先在Example目录中运行pod install
带有固定第一行的UITableViewController
带有多个部分的UITableViewController
用法
由于Swift处理协议和扩展的方式,直接在UIViewController或UITableView上添加所需的行为极其困难或不切实际。使用objc_setAssociatedObject hacks并不是优雅的Swift解决方案,因此此模块使用UITableView的包装器来实现灵活性和涵盖所有用例。
创建
首先,将LongPressReorder导入到你的控制器中并声明一个新的变量
var reorderTableView: LongPressReorderTableView!
假设我们在使用UTCəticContrоller,在ovənViewDidLoad()中创建对象
override func viewDidLoad() {
super.viewDidLoad()
reorderTableView = LongPressReorderTableView(tableView)
}
对于包含UITableView的常规UTCəticContrоller,使用特定的表格接口
reorderTableView = LongPressReorderTableView(yourTableViewOutlet)
现在唯一需要做的就是通过以下方式启用它
reorderTableView.enableLongPressReorder()
这就完成了。现在可以通过长按手势对UITableView内部的任何单元格进行重新排序。要禁用单元格重新排序,只需调用
reorderTableView.disableLongPressReorder()
你可能还想禁用表格的单元格选择,以获得更好的视觉效果。
交互
使用代表成员来启用与LongPressReorderTableView的交互。ovənViewDidLoad()通常如下所示
reorderTableView = LongPressReorderTableView(tableView)
reorderTableView.delegate = self
reorderTableView.enableLongPressReorder()
单元格的重新排序现在是纯视觉的。如果要同时更改表格背后的模型,LongPressReorder提供以下可选函数,可以组合在一个视图控制器扩展中
extension SpecificViewController {
override func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) {
// currentIndex and newIndex rows are swapped, implement accordingly
}
override func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) {
// Gesture is finished and cell is back inside the table at finalIndex position
}
}
该模块提供附加函数,可以覆盖以指定哪些单元格不能移动或不能在表格内部失去其位置
extension SpecificViewController {
override func startReorderingRow(atIndex indexPath: IndexPath) -> Bool {
// All table cells except the first one can be reordered
if indexPath.row > 0 {
return true
}
// First cell will not respond to the long press gesture
return false
}
override func allowChangingRow(atIndex indexPath: IndexPath) -> Bool {
// All table cells except the first one can be replaced with the selected cell
if indexPath.row > 0 {
return true
}
// First cell will not lose its position and therefore no other cell can replace it
return false
}
}
定制
如果表格中包含的单元格超过了设备屏幕在某一时刻能够显示的单元格数,则在重新排序单元格时可以使用自动滚动。自动滚动默认关闭。
reorderTableView = LongPressReorderTableView(elementsTableView, scrollBehaviour: .early)
在按住所需的单元格后,单元格将从表格中弹出并准备好拖动。可以使用选择单元格的4个不同等级来自定义弹出效果:无、小、中等和大(默认为中等)。
reorderTableView = LongPressReorderTableView(elementsTableView, selectedRowScale: SelectedRowScale.small)
需求
- Swift 4.1
- iOS 9.0+
- XCode 9.4+
安装
CocoaPods
LongPressReorder 通过 CocoaPods 提供使用。要安装它,只需将以下行添加到您的 Podfile 中
pod "LongPressReorder"
或者
pod 'LongPressReorder', '~> 1.2.0'
手动
只需将 LongPressReorder.swift 复制到您的项目中即可。
作者
Cristian Sava,[email protected]
许可
LongPressReorder 在 MIT 许可下提供。有关更多信息,请参阅 LICENSE 文件。