Quoting from Apple 's own documentation :
For performance reasons, only cell attributes should be reset. non-content related , such as alpha, editing and selection status.
for example, if a cell was selected, you simply set it as unselected, if you changed the background color to something, then you simply return it to the default color.
The table view delegate in tableView(_:cellForRowAt:) should always discard all content when reusing a cell.
This means that if you tried to set profile images in your contact list, you should not try to use nil images in prepareforreuse , you should set the images correctly in cellForRowAt , and if you did not find the image then you set its image to nil or the default image . Basically cellForRowAt should manage both expected and unexpected status.
Therefore, basically the following is not suggested:
override func prepareForReuse() { super.prepareForReuse() imageView?.image = nil }
Instead, the following is recommended:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.imageView?.image = image ?? defaultImage // unexpected situation is also handled. // We could also avoid coalescing the 'nil' and just let it stay 'nil' cell.label = yourText cell.numberOfLines = yourDesiredNumberOfLines return cell }
Additionally, it is recommended to use elements that are not related to the default content, as shown below:
override func prepareForReuse() { super.prepareForReuse() isHidden = false isSelected = false isHighlighted = false }
This is the method proposed by Apple. But to be honest, I still think it's easier to drop everything inside cellForRowAt , as Matt said. Clean code is important, but it really won’t help you achieve this. But, as Connor said, the only time needed for this is if you need to cancel the image upload. See here for more details.
those. do something like:
override func prepareForReuse() { super.prepareForReuse() imageView.cancelImageRequest()
Additionally, in the special case of using RxSwift: See here or here.