在使用tableView(moveRowAt:)
方法对行进行重新排序时,如果发现TableView的行高缩小,可能是由于以下几个原因导致的:
以下是一些可能的解决方案:
在调用moveRowAt(_:to:)
方法后,确保数据源也进行了相应的更新。
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// 假设你的数据源是一个数组
let movedObject = yourDataSource[sourceIndexPath.row]
yourDataSource.remove(at: sourceIndexPath.row)
yourDataSource.insert(movedObject, at: destinationIndexPath.row)
// 更新TableView
tableView.moveRow(at: sourceIndexPath, to: destinationIndexPath)
}
在移动行后,可以尝试重置TableView的行高缓存。
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// 更新数据源
let movedObject = yourDataSource[sourceIndexPath.row]
yourDataSource.remove(at: sourceIndexPath.row)
yourDataSource.insert(movedObject, at: destinationIndexPath.row)
// 移动行
tableView.moveRow(at: sourceIndexPath, to: destinationIndexPath)
// 重置行高缓存
tableView.reloadData()
}
如果行高变化是由于自动布局引起的,可以考虑使用固定的行高。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0 // 设置一个固定的行高
}
如果行高是动态计算的,可以使用estimatedRowHeight
来优化性能。
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableView.automaticDimension
以下是一个完整的示例,展示了如何在移动行时确保行高不变:
class YourViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var yourDataSource = [YourDataType]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableView.automaticDimension
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath)
// 配置cell
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = yourDataSource[sourceIndexPath.row]
yourDataSource.remove(at: sourceIndexPath.row)
yourDataSource.insert(movedObject, at: destinationIndexPath.row)
tableView.moveRow(at: sourceIndexPath, to: destinationIndexPath)
}
}
通过以上方法,可以有效解决在使用tableView(moveRowAt:)
方法时行高缩小的问题。
领取专属 10元无门槛券
手把手带您无忧上云