- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用许多自定义实现的 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/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPat
我正在使用表格 View 来显示从服务器加载的文本字段数组,所以我有一个表格 View 字段列表,当我填充这些数据字段并向下滚动以填充其他字段时,当我再次向上滚动时,我发现值发生变化并且存在重复值 -
我正在使用许多自定义实现的 UITableViewCell 子类。每个都包含这段代码 class CustomCell: UITableViewCell { static va
我有两个单元格: 像taskcella, taskcellb 但它动态地只返回 1 个单元格数据 是否可以添加并返回多个单元格标识符? public override UITableViewCell
谁能解释一下 static NSString* CellIdentifier = @"Cell"; 和 NSString *CellIdentifier = [NSString stringWithF
我的项目中没有 xib 文件或 Storyboard。在这种情况下,我该如何设置小区标识符?下面是我的代码: - (UITableViewCell *)tableView:(UITableView *
我正在尝试了解 [tableView dequeueReusableCellWithIdentifier:CellIdentifier] 的工作原理。这是我的情况: 我已经在 IB 中设计了我的 UI
在我的 tableview 中有我从 UITableViewCell 类初始化的自定义单元格。我有记录首字母的部分,并且有一个动态创建的 indexPath。 我想在我的表格 View 中添加一个搜索
我总是看到 UITableViewController 声明的样板 static NSString *CellIdentifier 在 - (UITableViewCell *)tableView:(
我的if语句中不断收到Expected Identifier - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtI
我尝试使用 RxSwift (3.6.1) 设置 tableView 数据源绑定(bind),但在构建应用程序时遇到错误: Ambiguous reference to member 'items(c
我在 ViewController 中有一个 CollectionView,我试图从 Realm 获取对象列表并使用 RxSwift 将其绑定(bind)到 CollectionView。 问题是我收
我是一名优秀的程序员,十分优秀!