2016-12-17 49 views
0

我已經嘗試了多種方法嘗試在Swift 3中獲得一個簡單的標題和消息表單元格。這是我得到的最遠和最接近的工作。我在我的應用程序委託文件的第一行出現Thread 1: Signal SIGABRT錯誤,在控制檯輸出中出現libc++abi.dylib: terminating with uncaught exception of type NSException錯誤。斯威夫特3自定義單元格帶來錯誤

單元類。插座連接到我的故事板文件中的原型單元。

import UIKit 
class MyTableCell: UITableViewCell { 
    @IBOutlet weak var label1: UILabel! 
    @IBOutlet weak var label2: UILabel! 
} 

代碼加載表

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyTableCell 

    if cell == nil { 
     let cell:MyTableCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MyTableCell 
     cell.textLabel?.text = posts[indexPath.row].title 
     cell.detailTextLabel?.text = posts[indexPath.row].message 
     return cell 
    } else { 
     cell.label1.text = posts[indexPath.row].title 
     cell.label2.text = posts[indexPath.row].message 
    } 



    return cell 
} 

注:我發現上面的代碼在線裝載表。這是我下面更簡單的代碼,無法正常工作。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell:MyTableCell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as! MyTableCell 

    cell.label1.text = posts[indexPath.row].title 
    cell.label2.text = posts[indexPath.row].message 

    return cell 
} 
+0

'1).'使你的代碼與錯誤的行停止添加一個異常斷點。 '2).'將異常記錄中的相關行(即導致應用程序停止的特定錯誤)添加到問題中。 '3).'你可能想要更新版本的'dequeueReusableCell':'let cell:MyTableCell = self.tableView.dequeueReusableCellWithIdentifier(「Cell」,forIndexPath:indexPath)as! MyTableCell'保證不爲零。 '4).'檢查你在Storyboard中設置了正確的單元格標識符,並且你的自定義單元格的類是正確的。 –

+0

你能解決這個問題嗎? –

+0

@RoboticCat不是最新版本,因爲快速修復將它更新爲'let cell:MyTableCell = self.tableView.dequeueReusableCell(withIdentifier:「Cell」,for:indexPath)as! MyTableCell'這是我原來的問題。 –

回答

0

如果nil返回調用tableView.dequeueReusableCell時,必須使用指定的UITableViewCell初始化實例化細胞。你提供的代碼轉過來再次調用tableView.dequeueReusableCell,這將再次返回零。

初始化一個新的電池,使用以下命令:

let cell = MyTableCell(style: .default, reuseIdentifier: "MyTableCell")

+0

我該怎麼做? –

+0

這給我一個'線程1:EXC_BAD_INSTRUCTION(code = EXC_1386_INVOP,子代碼= 0x0)'錯誤在我的下一行。 –

+0

如果你想使用'detailTextLabel',你必須使用'value1','value2'或'subtitle'的風格。 – damacster