2016-05-31 23 views
0

我目前有兩個UITableView s填充了應用程序的聯繫人。我有一個只是查看他們和編輯/刪除和一個從列表中搜索/選擇聯繫人。但是,當我嘗試使用UITableView s的相同自定義類單元格時,我得到一個返回的零值。使用相同的自定義單元實現兩個UITableView以便重用

這些是我的兩個cellForRowAtIndexPath函數。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCellWithIdentifier("SecondCell") as! ContactCell 
    let item = contacts[indexPath.row] 
    cell.meetupLabel?.text = item.fullName 
    return cell 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCellWithIdentifier("FirstCell") as! ContactCell 
    let item = contacts[indexPath.row] 
    cell.label?.text = item.fullName 
    return cell 
} 
+0

您確定在IB中爲您的單元設置了不同的標識符(SecondCell/FirstCell)嗎?我 –

回答

1

如果表中沒有一個名爲FirstCellSecondCell細胞,該dequeueReusableCellWithIdentifier(_:)方法將返回nil,你需要自己構建的細胞。

// no don't do this. 
let cell: ContactCell 
if let c = tableView.dequeueReusableCell(withIdentifier: "FirstCell") as? ContactCell { 
    cell = c 
} else { 
    cell = ContactCell(style: .default, reuseIdentifier: "FirstCell") 
} 

您應該使用dequeueReusableCell(withIdentifier:for:),這是在iOS 6中推出,如果您想的UIKit來構建你的細胞:

// swift 3 
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", 
       for: indexPath) as! ContactCell 

// swift 2 
let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell", 
       forIndexPath: indexPath) as! ContactCell 
... 

另外,請檢查您是否已經給出了正確的在界面構建器中正確使用重用標識符。

enter image description here

+0

我懷疑你的答案的最後一部分是關鍵:當你在IB設置你的表視圖或它不起作用時,必須將重用標識符分配給單元格。 –

+0

神奇,它的作品。它總是看起來很小的事情。謝謝! – ggworean

+0

@ggworean這不應該發生,如果你註冊的UITableView的類。檢查'registerNib'或'registerClass'方法 –

0

正如你說你是getting nil,我快速的猜測是,你還沒有註冊在某些時候細胞,早於該小區的事件運行。看看this thread on how to register cell

+0

因爲我正在通過IB來執行重用標識符,所以我不需要註冊這個類。這實際上會導致衝突。 – ggworean

相關問題