import UIKit
class ViewController: UIViewController {
let reuseableCellPool = ReusableCellPool(capacity: 5)
override func viewDidLoad() {
super.viewDidLoad()
for i in 0...5 {
let cell = Cell(name: "\(i)")
reuseableCellPool.enqueue(withIdentifier: "reusedCell", cell: cell)
}
for i in 0...5 {
if let cell = reuseableCellPool.dequeueReuseableCell(withIdentifier: "reusedCell") {
cell.printOut()
}
}
}
}
class Cell {
var name: String
init(name: String) {
self.name = name
}
func printOut() {
print("l am cell \(name)")
}
}
class ReusableCellPool {
private var reusableCell: [String: [Cell]] = [:]
private let lock = NSLock()
private let capacity: Int
init(capacity: Int) {
self.capacity = capacity
}
func dequeueReuseableCell(withIdentifier: String) -> Cell? {
lock.lock()
defer { lock.unlock() }
if var cells = reusableCell[withIdentifier], let cell = cells.popLast() {
reusableCell[withIdentifier] = cells
return cell
}
return nil
}
func enqueue(withIdentifier: String, cell: Cell) {
lock.lock()
if var cells = reusableCell[withIdentifier] {
if cells.count <= capacity {
cells.append(cell)
reusableCell[withIdentifier] = cells
}
} else {
reusableCell[withIdentifier] = [cell]
}
lock.unlock()
}
}
相信大家看完这里,应该对UITableViewCell的复用机制有了更深一步的了解了吧,下面我们一起来看一下UITableView的复用代码吧
// 假设 tableView 是 UITableView 实例,cellIdentifier 是单元格的重用标识符
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 从复用池中获取可重用的单元格
let cell: UITableViewCell
if let reusableCell = cellPool.dequeueReusableCell(withIdentifier: cellIdentifier) {
cell = reusableCell
} else {
// 如果复用池中没有可用的单元格,则创建一个新的单元格
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
//换成我上面的代码就是 cell = Cell(name: "")
}
// 设置单元格的内容
// ...
return cell
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 在单元格离开屏幕时,将单元格放回复用池中
cellPool.enqueue(cell, withIdentifier: cellIdentifier)
}
大家喜欢的可以点点关注哈,博主最近会更新滴!