您可以使用 Set<IndexPath> 和您的 tableView 委托方法来实现此目的。
假设您有一组选定的索引路径selectedIndexPaths 和高度largeHeight 和normalHeight。您的 heightForRow 函数可能如下所示:
func tableView(_ tableView: UITableView, heigthForRowAt indexPath: IndexPath) -> CGFloat {
guard !selectedIndexPaths.contains(indexPath) else {
return largeHeight
}
return normalHeight
}
然后您可以通过以下方式动态更改高度:
/// Convenience method for selecting an index path
func select(indexPath: IndexPath, completion: ((Bool) -> Void)? = nil){
selectedIndexPaths.insert(indexPath)
tableView.performBatchUpdates({
self.tableView.reloadRows(at: [indexPath], with: .none)
}, completion: completion)
}
在您的 tableView 委托中,您可以在 didSelect 中调用此方法:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
select(indexPath: indexPath)
}
如果您有响应通知的方法(假设您将 indexPath 放在通知的 userInfo 中,在键“indexPathKey”下),请执行相同操作:
func notifiedShouldEnlargeRow(aNotification: Notification) {
guard let indexPath = aNotification.userInfo["indexPathKey"] as? IndexPath else { return }
select(indexPath: indexPath)
}
作为参考,请查看performBatchUpdates(_:completion) 和reloadRows(at:with:)。