2016-02-13 76 views
0

你好我有一個動態原型TableView。我添加了4個原型單元。三個是靜態的,一個是動態的。問題是我得到數組索引超出範圍錯誤。你能否檢查一下哪裏出了問題。什麼應該是行的總數,我應該分配致命錯誤:數組索引超出範圍在TableView

let NUMBER_OF_STATIC_CELLS = 3 
var labels = ["label1","label2","label3"] 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 


    return labels.count+NUMBER_OF_STATIC_CELLS 



} 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 



    var cell: TestViewCell! 

    print(indexPath.row) 
    if (indexPath.row == 0) { 
     cell = tableView.dequeueReusableCellWithIdentifier("static1", forIndexPath: indexPath) as! TestViewCell 


    } 

    if (indexPath.row == 1) { 
      cell = tableView.dequeueReusableCellWithIdentifier("static2", forIndexPath: indexPath) as! TestViewCell 
     //cell.cardSetName?.text = self.cardSetObject["name"] as String 
     } 

    if (indexPath.row == 2) { 
      cell = tableView.dequeueReusableCellWithIdentifier("static3", forIndexPath: indexPath) as! TestViewCell 
      //cell.cardSetName?.text = self.cardSetObject["name"] as String 
     } 




     if (indexPath.row >= 3) { 

     cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TestViewCell 
     cell.testLabel.text = labels[indexPath.row] // return test rows as set in numberOfRowsInSection 
    } 

    return cell; 
    } 
+1

FYI,蘋果在他們的Swift文件註釋常數應該顛倒駱駝情況.....並非所有帽。這只是一個C的東西:/。爲你的行檢查使用開關盒,這將清理你的代碼..很多。 – TheCodingArt

+0

仍舊損壞,更新後的邏輯嘗試訪問索引3,4和5,這些索引超出了範圍。嘗試'標籤[indexPath.row - NUMBER_OF_STATIC_CELLS]'。還要將'> = 3更改爲> = NUM​​BER_OF_STATIC_CELLS'。另外,@TheCodingArt關於常量情況的說法 –

+0

另外,我強烈建議你花更多的努力來保持縮進的一致性 - 當你不這樣做時,讓自己變得更難 - 你所有的if都應該縮進同一級別 - 掃描你的代碼的人看起來像你嵌套'ifs'當你不 –

回答

1

您已設置細胞的數量將是6和標籤陣列,你只有3個單元。此外,在你分配給單元格的每個條件中,但在方法的最後,你將覆蓋那個(我想)不是你的意圖。然後,您嘗試訪問超出索引的索引

+0

對不起,我已經更新了我的問題。請看看 – hellosheikh

+0

還是一樣的問題。在最後一個條件中,您正在訪問索引3,4 ...中只有3個元素的數組中的元素。這就是您的應用崩潰的原因。把斷點和檢查值,你會發現這個問題 –

+0

所以我應該怎麼辦?還有我有三個靜態的細胞和細胞的其餘部分將是動態的。所以這意味着第四之一。請你能告訴我應該有多少行定義。 – hellosheikh

0

這是您的錯誤!你有沒有標籤索引2以上。下面的行試圖做標籤[3]等

cell.testLabel.text = labels[indexPath.row]