2016-11-20 84 views
-2

我嘗試使用下面的代碼返回行的表中的次數:「未能獲得細胞」錯誤試圖使用一個UITableView

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    let count = FirstTableArray.count 
    print(count)//prints 5 
    return count 
} 

它不會工作給予以下錯誤

2016年11月20日13:28:46.787 ModularProject [10870:2357799] *斷言故障 - [UITableView的_configureCellForDisplay:forIndexPath:],/BuildRoot/Library/Caches/com.apple.xbs/Sources /UIKit_Sim/UIKit-3600.5.2/UITableView.m:8035 2016-11-20 13:28:46.829 ModularProject [10870:2357 799] *由於未捕獲的異常'NSInternalInconsistencyException',原因:'UITableView(; layer =; contentOffset:{0,-64}; contentSize:{375,44}>)無法從其dataSource()中獲取單元格'

我無法理解爲什麼強制0作爲返回變量的作用而不是1?

編輯1:

這裏是我的參考

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    print("runs") 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    print("runs2") 
    cell.textLabel?.text = "Foo" 
    return cell 
    print("runs3") 
} 
+5

你執行的cellForRowAtIndexPath? – Adeel

+0

是的,我做了以後 –

+0

後你發生了什麼實現它? – Adeel

回答

-1

cellForRowAt方法您檢查您的代理和數據源?

self.tableView.delegate = self 
self.tableVie.dataSource = self 

不知道你是否知道,但你必須把你的課程放在你的班級?

class MyClass: UIViewController, UITableViewDelegate, UITableViewDataSource {} 
+0

你的回答沒有任何關係,在這個問題的錯誤。如果數據源未設置,表格將只顯示沒有行。不會有任何錯誤。如果協議沒有在'class'行設置,那麼當設置'dataSource'和'delegate'屬性時,代碼就不會編譯。 – rmaddy

+0

@rmaddy如果您直接從故事板**設置'dataSource'和'委託'**並且**不符合類到協議,代碼將編譯並導致崩潰OP正面臨。不知道這是否是答案作家的意思。 – Rikh

0

強制0的作品,因爲這樣的tableView認爲它有沒有行顯示,因此它不會嘗試調用cellForRowAt方法。

因此,如果您要使用任何數字1或更大,則必須實施UITableViewDataSource所要求的cellForRowAt。這裏有一個例子:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
    cell.textLabel?.text = "Foo" 
    return cell 
} 

假設你正在使用的故事板,請確保您的代碼,我已經在本例中爲「細胞」在這裏設置你的小區標識,以匹配任何你用作故事板中的單元格標識符。

0

首先檢查您是否獲得手機的零在

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

如果對象返回零

let object = line. If the problem is that tableView.dequeueReusableCell(withIdentifier:) // check object here, if nil then 

如果你使用,你會爲你做了一個原型細胞現代化的Xcode模板,你應該用這個代替:

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

如果你沒有使用Xcode temp後期,使用該行代碼反正然後註冊自己的再利用標識符是這樣的:

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") 

一切順利的話應該可以解決這個問題。如果沒有,請檢查單元格標識符是否正確:默認情況下它是「單元格」,但您可能已更改它。當tableView.dequeueReusableCell(withIdentifier:)失敗時,這樣的拼寫錯誤應該導致崩潰,但無論如何它值得檢查。

讓我知道這對你的工作。

+0

嘿,我理解你的意見,但它似乎仍然沒有工作。故事板中的標識符單元格是正確的,您使用的代碼與我的相同,請參閱主要問題編輯。它打印運行,但不運行2顯示錯誤是與「dequeueReusableIdentifier」行 –