gpt4 book ai didi

ios - 获得正确 reuseIdentifier 的问题

转载 作者:行者123 更新时间:2023-11-28 13:37:41 24 4
gpt4 key购买 nike

我已经为 UITableView 创建了一个扩展,并希望在运行时获得正确的 reuseIdentifier,但我不能:

extension UITableView {

func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {

let s = T.reuseIdentifier

变量“s”始终包含“UITableViewCell”,而不是我在 Storyboard中指定的名称。

最佳答案

没关系,整个方法

extension UITableView {

func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
return self.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
}
}

应该可以正常工作。


另一种方法是协议(protocol)扩展和static 方法,只需在UITableViewCell 子类中采用该协议(protocol)即可。

protocol Reusable {
associatedtype CellType : UITableViewCell = Self

static var cellIdentifier : String { get }
static func dequeueReusableCell(in tableView : UITableView, for indexPath: IndexPath) -> CellType
}

extension Reusable where Self : UITableViewCell {

static var cellIdentifier : String {
return String(describing: Self.self)
}

static func dequeueReusableCell(in tableView : UITableView, for indexPath: IndexPath) -> CellType {
return tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CellType
}
}

然后调用它

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = MyTableViewCell.dequeueReusableCell(in: tableView, for: indexPath)
...

关于ios - 获得正确 reuseIdentifier 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56405532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com