2015-08-08 28 views
0

我正在嘗試爲我的大部分應用代碼使用CoreData變量,但一直未能將它們用於自定義類的名稱。這裏是我的代碼示例:Swift:是否可以使用變量作爲自定義類名稱?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CREWWorkCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier(cellName) as! CREWWorkCell 

我想爲CREWWorkCell使用字符串。這可能嗎?

回答

1

UITableViewController沒有函數返回CREWWorkCell您可以覆蓋。使用默認的UITableViewCell作爲返回值,並且對於自定義單元格,一切都可以正常工作。

在你的UITableViewController類中使用下列功能:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Note that the return value is UITableViewCell and not CREWWorkCell 

     //get the class name from the database and put it in a variable called myClassName. Then 

     if myClassName == "CREWWorkCell" { 
      let cell : CREWWorkCell = tableView.dequeueReusableCellWithIdentifier("cell identifier 1", forIndexPath: indexPath) as! CREWWorkCell //of course you should cast to your custom class to be able to use it 
      return cell 
     } else if myClassName == "AnotherCellClass" { 
      let cell : AnotherCellClass = tableView.dequeueReusableCellWithIdentifier("cell identifier 2", forIndexPath: indexPath) as! AnotherCellClass 
      return cell 
     } 

     //do the same if you have other custom classes etc... 

     return UITableViewCell() 
    } 

與SWIFT不能轉換爲動態類型(看看here)。因此,你無法投射到您在可變投入使用例如類型:

var myClassName = CREWWorkCell.self 

var myClassName = CREWWorkCell().dynamicType 

因爲myClassName會在運行時進行評估,換句話說,它是一個動態類型。但鑄造操作員期望其右手邊靜態類型,這是一種已知的類型,不需要在運行時進行評估。該功能允許Swift強制執行類型安全。

我建議你以一種更簡單的方式重新思考你創建自定義單元格的方式。

+0

由於我需要使用單元格的自定義類,我不明白我該怎麼做。 – PatriciaW

+0

CREWWorkCell已經是UITableViewCell的子類。它工作得很好 – Carpsen90

+0

如果我有多個子類,我該如何指定使用哪一個?每個單元格中的對象都在其中指定。 – PatriciaW

相關問題