2015-09-18 21 views
1

我正在使用一些自定義實現的UITableViewCell子類。 每個包含這段代碼在swift中生成的CustomTableViewCell cellIdentifier擴展名不可能?

class CustomCell: UITableViewCell { 

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

我下面的設計原則是用於特定小區的cellIdentifier總是相匹配的細胞class'es名稱和關聯XIB文件也具有相同的名稱。

CellClassName == CellXibName == CellIdentifier。

我想避免只有字符串常量定義 - 神知道哪裏爲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 :-/) 

回答

1

更簡潔的解決方案:

創建一個名爲類似「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/

希望這有助於。