2014-08-29 24 views
6

我有一個表格視圖與創建爲.xib的自定義單元格。我沒有使用故事板。我有一個問題,我無法用webservice結果中的數據填充表格。另外,我在自定義單元格中有4個標籤。在我的自定義單元類中,當我嘗試爲每個項目設置標籤時,它會給我上面的致命錯誤。自定義單元格:致命錯誤:意外地發現零,同時展開一個可選值

這裏是我的代碼:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
... 

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! 
{ 
     let cell: ItemManagementTVCell = tableView?.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell 

    if let ip = indexPath 
    { 
     let item: Item = self.itemList[indexPath.row] as Item 
     cell.setCell(item.itemName, status: item.itemStatus, duration: item.itemDuration, price: item.itemPrice) 
    } 
    return cell 
} 
} 

我的自定義單元格類是在這裏:

進口的UIKit

class ItemManagementTVCell: UITableViewCell { 

    @IBOutlet var lblItemName: UILabel! 
    @IBOutlet var lblItemPrice: UILabel! 
    @IBOutlet var lblItemDuration: UILabel! 
    @IBOutlet var lblItemStatus: UILabel! 

    override func awakeFromNib() 
    { 
     super.awakeFromNib() 
    } 

    override func setSelected(selected: Bool, animated: Bool) 
    { 
     super.setSelected(selected, animated: animated) 
    } 

    func setCell(name: String, status: Int, duration: Int, price: Int) 
    { 
     self.lblItemName.text  = name 
     self.lblItemStatus.text = String(status) 
     self.lblItemDuration.text = "Duration: \(String(duration)) months" 
     self.lblItemPrice.text = String(price) + " $" 
    } 
} 

我得到 「setCell」 方法塊內的誤差。

我已閱讀了很多問題和解決方案,我嘗試了所有這些方法並不適合我。

感謝您的回答,

此致敬意。

SOLUTION:我已經通過將單元格項鍊接到單元格自己而不是鏈接到文件所有者來解決此問題。我的問題已經通過這樣做了。

+0

你能在這裏添加的解決方案? – neosergio 2014-11-26 20:31:16

+0

這很簡單,我會一步一步解釋1-)點擊你的單元格2-)點擊位於右側的「隱藏或顯示實用工具」菜單中的連接檢查器。 3-)點擊文件的所有者,如果有任何連接的項目,刪除所有。然後點擊單元格視圖並在那裏連接你的單元格。注意:我沒有使用故事板。這個解決方案適用於xibs。 @neosergio – user2174358 2014-11-27 13:17:47

+0

謝謝你的澄清 – neosergio 2014-11-27 19:51:34

回答

7

您的「單元格」必須爲零。

使用

tableView.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell 

可以返回零。您應該使用:

tableView.dequeueReusableCellWithIdentifier("cell" forIndexPath:indexPath) as ItemManagementTVCell 

這樣可以保證單元不爲零。

編輯:也許你可以通過把如果「setCell」

if var itemName = self.lblItemName { 
    itemName.text = name 
} 

內聲明做,對於每一個你裏面的設置,並檢查是否崩潰仍然發生標籤防止死機。如果不是,你必須檢查爲什麼這些標籤是零。

+0

謝謝你的回答,但問題仍然存在。 – user2174358 2014-08-29 13:55:52

+0

你可以在setCell塊中放置一個斷點,並檢查裏面的東西是否爲「無」? – 2014-08-29 13:58:52

+0

也許「item」是零。 – 2014-08-29 14:04:46

4

另一種解決問題的方法,而無需電池項目鏈接到小區業主:

let nib = UINib(nibName: "YOUR_CUSTOM_CELL_NIB_NAME", bundle: nil) 
tableView.register(nib, forCellReuseIdentifier: "YOUR_CUSTOM_CELL_ID") 
相關問題