dequeueReusableCell 傳入 cell reuse id 的幾種寫法
Published in
6 min readAug 26, 2021
以下說明 collection view cell 的例子,table view cell 也是一樣的做法。
方法 1: 使用 string interpolation
將 reuse id 定義成 cell 的類別,比方 CollectionViewCell,然後用 "\(CollectionViewCell.self)"
產生字串 CollectionViewCell。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(CollectionViewCell.self)", for: indexPath) as! CollectionViewCell
return cell
}
方法 2: 另外定義型別,宣告 type property 儲存 reuse id
class CollectionViewController: UICollectionViewController {
struct PropertyKeys {
static let reuseIdentifier = "CollectionViewCell"
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PropertyKeys.reuseIdentifier, for: indexPath) as! CollectionViewCell
return cell
}
方法 3: 在檔案裡宣告 private constant
private let reuseIdentifier = "CollectionViewCell"
class CollectionViewController: UICollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
return cell
}
方法 4: 在 cell 裡宣告 type property
type property 可宣告成 stored property 或 computed property。
- stored property
class CollectionViewCell: UICollectionViewCell {
static let reuseIdentifier = "\(CollectionViewCell.self)"
}
- computed property
class CollectionViewCell: UICollectionViewCell {
static var reuseIdentifier: String { "\(Self.self)" }
}
dequeueReusableCell 時傳入 CollectionViewCell.identifier。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseIdentifier, for: indexPath) as! CollectionViewCell
return cell
}
方法 5: 使用 extension
所有的 collection view cell 都有 type property reuseIdentifier。
extension UICollectionViewCell {
static var reuseIdentifier: String { "\(Self.self)" }
}
dequeueReusableCell 時傳入 CollectionViewCell.reuseIdentifier。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseIdentifier, for: indexPath) as! CollectionViewCell
return cell
}
方法 6: 直接輸入字串
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
return cell
}