我有一個帶有 2 個 3 行原型單元格的表格視圖。第一個原型單元只有一個視圖。第二個原型單元有一個按鈕。第一個原型單元格只有 1 行,這也是第一個 indexpath.row 第二個原型單元格有 2 行。(第二和第三個 indexpath.row )
我想將我的模型(陣列)與第 2 行和第 3 行合并。但是應用程式崩潰并說超出范圍。
表視圖類
let modelArray = [phone, remote]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 modelArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
if indexPath.row < 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL1", for:
indexPath) as! CELL1
cell.view.backgroundColor = .red
return cell
}
let cell2 = tableView.dequeueReusableCell(withIdentifier: "CELL2", for: indexPath)
CELL2
這是我得到超出范圍錯誤的地方。(我也試過沒有 1 )
cell2.configure(title: modelArray[indexpath.row 1])
return cell2
}
CELL2級
@IBOutlet weak var buttonName: UIButton!
private var title: String = ""
func configure(title: String) {
self.title = title
buttonName.setTitle(title, for: .normal)
}
uj5u.com熱心網友回復:
因為您的 modelArray 只有 2 個元素,而您正試圖獲得第三個元素值。
讓我們假設 whenindexPath
是 0 然后tableview
渲染 CELL1 并且 whenindexPath
遞增,我們可以說它 whenindexPath
是 1 然后你從你的 modelArray 中獲取值,如下所示:
cell2.configure(title: modelArray[indexpath.row 1])
它得到的值 modelArray[1 1] 轉入 modelArray[2] 但 modelArray 不包含 modelArray[2],它只有 0 和 1 元素。
通過從 current 中減去 1 來嘗試使用indexPath
。
cell2.configure(title: modelArray[indexpath.row - 1])
uj5u.com熱心網友回復:
請看邏輯: cellForRow
被呼叫了 3 次 (1 2),但陣列中索引 3 處沒有專案(也沒有沒有 索引 2 處 1
)。
根據代碼,單元格indexPath.row == 1
應該顯示陣列中的第一項(索引 0)和indexPath.row == 2
第二項(索引 1)的單元格。
所以你必須減去1
cell2.configure(title: modelArray[indexpath.row - 1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/382261.html