将多个自定义TableViewCell Xib索引到TableView

时间:2019-11-07 17:57:28

标签: ios swift xcode uitableview indexpath

我正在创建一个TableView,它从顶部的图像,大约5个解析的json单元格,另一个图像,大约3个以上的解析的json单元格和另一个图像开始。

我有3个正在使用的自定义笔尖。每个人都是独一无二的。

在“让item = page?.collapsibles [indexForSecondSetTableViewCells]”行上出现“索引超出范围”错误

这是我的代码:

struct questionOne: View {

   var body: some View {
        GeometryReader { geometryProxy in
            VStack(alignment: .center, spacing: 20) {

                TRpic().frame(maxWidth: geometryProxy.size.width, alignment: .center)
                       .padding([.leading, .trailing], 10)
                  .......               
            }  
        }
   }

更新:我将代码简化为使用相同的json对象两次,以便每个项目都精确映射到它应该去的单元格,并且在第7行仍然出现“致命错误:索引超出范围”错误, func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let currentIndex = indexPath.row - 1 let numberofCarousels = self.page?.carousels.count let indexAfterCarousels = numberofCarousels ?? 00 + 1 let indexForSecondSetTableViewCells = indexAfterCarousels + 1 if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "pipesOne", for: indexPath) as! Pipes1TableViewCell cell.pipesOne.image = UIImage(named: "WhatsNew1") return cell } if indexPath.row == indexAfterCarousels { let cell = tableView.dequeueReusableCell(withIdentifier: "pipesOne", for: indexPath) as! Pipes1TableViewCell cell.pipesOne.image = UIImage(named: "WhatsNew2") return cell } if indexPath.row == indexForSecondSetTableViewCells { let cell = tableView.dequeueReusableCell(withIdentifier: "collapsibleCell", for: indexPath) as! CollapsiblesTableViewCell let item = page?.collabsible[indexForSecondSetTableViewCells] cell.collabsibleTitle.text = item?.title cell.collabsibleDescription.text = item?.content return cell } let cell = tableView.dequeueReusableCell(withIdentifier: "newsTableViewCell", for: indexPath) as! NewsTableViewCell let item = page?.carousels[currentIndex] cell.newsTitle.text = item?.title cell.newsText.text = item?.caption cell.newsImage.kf.setImage(with: page?.carousels[currentIndex].imageURL) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (page?.carousels.count ?? 0) + 1 + (page?.collapsibles.count ?? 0) }

新代码:

let item = page?.collapsible[indexPath.row]

1 个答案:

答案 0 :(得分:0)

尝试在

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

然后,您将知道崩溃前成功显示了多少行。 然后在cellForRowAt中放入条件断点,以使它在indexPath是崩溃的那个断点时停止。 现在开始po (page?.carousels.count ?? 0) + 1 + (page?.collapsibles.count ?? 0) 查看表格视图有多少行。绝对可以肯定,indexForSecondSetTableViewCells超过了行数