gpt4 book ai didi

ios - 无法快速生成 CustomTableViewCell cellIdentifier 扩展?

转载 作者:行者123 更新时间:2023-11-29 10:25:20 25 4
gpt4 key购买 nike

我正在使用许多自定义实现的 UITableViewCell 子类。每个都包含这段代码

    class CustomCell: UITableViewCell {

static var cellIdentifier : String {
return (NSStringFromClass(CustomCell.self) as NSString).lastPathComponent.componentsSeparatedByString(".").last!
}
}

我遵循的设计原则是特定单元格的 cellIdentifier 始终与单元格类的名称匹配,并且关联的 xib 文件也具有相同的名称。

CellClassName == CellXibName == CellIdentifier.

我试图避免只定义字符串常量——天知道 TableView 委托(delegate)在需要队列中的正确单元格时从何处获取。当我注册单元格时,我希望能够在类中查询表示单元格标识符的静态公共(public)属性。上面的代码给了我那个。然而,这显然是一个重复,因为我需要在每个 CustomCell 类中编写它。

你能帮我把它做成 UITableViewCell 的扩展吗?我无法具体弄清楚如何替换

NSStringFromClass(CustomCell.self)  

像这样的东西

NSStringFromClass(Something here, that will return the real instance's name 
as String, even if this code is in the extension :-/ )

最佳答案

更简洁的解决方案:

使用以下代码创建一个名为“UITableViewCellExtension.swift”的新文件:

import UIKit

extension UITableViewCell {

static var cellIdentifier : String {
return (NSStringFromClass(self) as NSString).lastPathComponent.componentsSeparatedByString(".").last!
}
}

所以这只会替换您问题中的代码:

NSStringFromClass(CustomCell.self)  

与:

NSStringFromClass(self)  

其他解决方案:

iOS9+解决方案

protocol Reusable {
static var reuseIdentifier: String { get }
}

extension Reusable {
static var reuseIdentifier: String {
let mirror = Mirror(reflecting: self)
return String(mirror.subjectType).stringByReplacingOccurrencesOfString(".Type", withString: "")
}
}

extension UITableViewCell : Reusable {
}

灵感来自 http://codica.pl/2015/08/11/protocol-extensions-and-reuseidentifier-in-uitableview/

希望这对您有所帮助。

关于ios - 无法快速生成 CustomTableViewCell cellIdentifier 扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653227/

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