2016-12-30 37 views
2

所以這裏是我面臨的問題。 看看如何使用字符串創建類參考

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if indexPath.row == 0 { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell_Title") as! ExpenseTableViewCell_Title 
     return cell 
    } else { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell_SaveCanel") as! ExpenseTableViewCell_SaveCanel 
     return cell 
    } 
} 

我想要做的是,使用小區標識字符串作爲細胞類型(即。ExpenseTableViewCell_Title,ExpenseTableViewCell_SaveCanel)。

我確實有細胞標識符數組。

var TableCell:[ExpenseCellType] = [.ExpenseTableViewCell_Title, .ExpenseTableViewCell_SaveCanel] 

現在我只有兩種類型的單元格。但是這個數字會很高。 而我不想使用if/else條件或切換大小寫。

提前致謝。

+0

Swift is str ict與類型檢查。所以你無法避免這一點。 – Lumialxk

回答

2

您可以使用函數NSClassfromString,但是您需要用於從String獲取類的名稱空間。

我已經在這裏創建示例來使用它。 例子:

func getClassFromString(_ className: String) -> AnyClass! { 


    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String; 
    let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!; 

    return cls; 
} 


    class customcell: UITableViewCell { 

     } 

    let requiredclass = getClassFromString("customcell") as! UITableViewCell.Type 
    let cellInstance = requiredclass.init() 
+0

感謝您的回答,但我可以找到任何名爲「stringClassFromString」的函數。儘管我曾嘗試過「NSClassFromString」。那也沒用。 – rv7284

3

能使其與擴展短:

extension UITableView { 
    func dequeueReusable<T>(type: T.Type, index: IndexPath) -> T { 
     return self.dequeueReusableCell(withIdentifier: String(describing: T.self), for: index) as! T 
    } 
} 

使用它像這樣,將返回ExpenseTableViewCell_Title類型的細胞:

let cell = tableView.dequeueReusable(type: ExpenseTableViewCell_Title.self, index: indexPath) 

類只是存儲像數組中[ExpenseTableViewCell_Title.self, ExpenseTableViewCell_SaveCanel.self]並將其傳遞給此函數

+0

謝謝,我會試試這個。 – rv7284