我有一個 UITableView,它用 NSFetchedResultsController 填充它的單元格。我還使用 indexPathsForVisibleRows 來更新可見單元格,除了我點擊和編輯的單元格。但是 UI 會使用正確的計算更新所有單元格,除了一個。如果我滾動該 tableView,那么該單元格會在下次它變得可見時重新計算。
有問題的 GIF:點擊
在那里,我定義了要編輯的單元格,并為除我正在編輯的單元格之外的所有單元格重新加載行:
func textFieldDidChangeSelection(_ textField: UITextField) {
let tapLocation = textField.convert(textField.bounds.origin, to: tableView)
guard let indexPath = tableView.indexPathForRow(at: tapLocation) else { return }
pickedCurrency = fetchedResultsController.object(at: indexPath)
let visibleIndexPath = tableView.indexPathsForVisibleRows ?? []
var nonActiveIndexPaths = [IndexPath]()
for index in visibleIndexPath where index != indexPath {
nonActiveIndexPaths.append(index)
}
tableView.reloadRows(at: nonActiveIndexPaths, with: .none)
}
為什么 UI 會更新除一個以外的所有單元格?找不到原因...
uj5u.com熱心網友回復:
這是我設法解決我的問題的方法。我的理解是我應該避免使用tableView.indexPathsForVisibleRows我的案例,因為正如@ShawnFrank 所說,它只會重新加載可見的單元格:
func textFieldDidChangeSelection(_ textField: UITextField) {
//Code for defining an active cell (on which I clicked to edit its textField)
let tapLocation = textField.convert(textField.bounds.origin, to: tableView)
guard let pickedCurrencyIndexPath = tableView.indexPathForRow(at: tapLocation) else { return }
pickedCurrency = fetchedResultsController.object(at: pickedCurrencyIndexPath)
//Array for all IndexPaths which is not selected, i.e. not active
var nonActiveIndexPaths = [IndexPath]()
//Define all rows tableView has at the moment for particular section
//In my case it can be only 1 section which starts at 0 index
let tableViewRows = tableView.numberOfRows(inSection: 0)
for i in 0..<tableViewRows {
//Create indexPath with the rows and section
let indexPath = IndexPath(row: i, section: 0)
//Add all IndexPaths to previously created array, except the one that is active now
if indexPath != pickedCurrencyIndexPath {
nonActiveIndexPaths.append(indexPath)
}
}
//Reload only rows from the array
tableView.reloadRows(at: nonActiveIndexPaths, with: .none)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427928.html
