Ios 无法在swift中生成CustomTableViewCell cellIdentifier扩展?

Ios 无法在swift中生成CustomTableViewCell cellIdentifier扩展?,ios,uitableview,swift2,Ios,Uitableview,Swift2,我正在使用许多自定义实现的UITableViewCell子类。 每个都包含这段代码 class CustomCell: UITableViewCell { static var cellIdentifier : String { return (NSStringFromClass(CustomCell.self) as NSString).lastPathComponent.componentsSeparatedByString(".").las

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

    class CustomCell: UITableViewCell {

        static var cellIdentifier : String {
            return (NSStringFromClass(CustomCell.self) as NSString).lastPathComponent.componentsSeparatedByString(".").last!
        }
    }
我遵循的设计原则是,特定单元的单元标识符始终与单元类的名称匹配,并且关联的xib文件也具有相同的名称

CellClassName==CellXibName==CellIdentifier

我试图避免在TableView委托需要从队列中获取正确的单元格时,只定义字符串常量,而TableView委托需要从哪里获取字符串常量。 当我注册单元格时,我希望能够在类中查询表示单元格标识符的静态公共属性。 上面的代码告诉了我。 然而,这显然是一个重复,因为我需要在每个
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)  
与:


其他解决方案:

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 {
}
灵感来自

希望这有帮助

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 {
}