Sobes.tech
Junior — Middle

How will you solve the problem of stalling when scrolling a UITableView?

sobes.tech AI

Answer from AI

Stuttering issues when scrolling a UITableView are usually related to performing heavy operations in the cellForRowAt method, which block the main thread. To resolve this, you can:

  • Use cell reuse with dequeueReusableCell.
  • Load and cache data in advance, such as images — use asynchronous loading with URLSession or third-party libraries like SDWebImage.
  • Minimize work in cellForRowAt, for example, avoid heavy data processing or calculations.
  • Use prefetchDataSource for preloading data before display.
  • Optimize cell layout, avoid complex calculations in layoutSubviews.

Example of asynchronous image loading in a cell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let url = URL(string: imageUrls[indexPath.row])!
    cell.imageView?.image = nil
    DispatchQueue.global().async {
        if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
            DispatchQueue.main.async {
                if let updateCell = tableView.cellForRow(at: indexPath) {
                    updateCell.imageView?.image = image
                    updateCell.setNeedsLayout()
                }
            }
        }
    }
    return cell
}