我想显示两种类型的单元格。两种类型的单元格都是显示来自 2 个不同 API 调用的数据。所以结构基本上是这样的:
Type A 仅出现 1 次,来自 API 方法 A,这是 TableView
的第一个单元格,其余的都是类型B,来自API方法B。
为了实现这个功能,我做了以下工作:
1) 在 StoryBoard 中,我这样设置 TableView
的结构:
MyTableView
-Type A Cell
--My others view..
-Type B Cell
--My others view..
2) 两个 Cell 都有它们的 TableViewCell
类。
3) 两个 Cell 都有自己的模型类来初始化 JSON
来自 API
最后在我的 ViewController 中有所有这些代码:
All the basic code here
//The NSObject class for both type of cell
var typeAArray = [TypeA]()
var typeBAarray = [TypeB]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.getTypeAData()
self.getTypeBData()
}
func getTypeAData(){
//code to call API,parse JSON and also append to `typeAArray`
//and reload TableView
}
func getTypeBData(){
//code to call API,parse JSON and also append to `typeBArray`
//and reload TableView
}
The code for TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return typeAArray.count + typeBArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let typeACell = tableView.dequeueReusableCell(withIdentifier: "TypeACell", for: indexPath) as! TypeATableCell
typeACell.data = self.typeAArray[indexPath.row] //Here I get index or of range error
return typeACell
}
let typeBCell = tableView.dequeueReusableCell(withIdentifier: "TypeBCell", for: indexPath) as! TypeBTableCell
typeBCell.data = self.typeBArray[indexPath.row]
return typeBCell
}
到目前为止我得到了什么:
现在有了上面的设置和代码,我在 if indexPath == 0
部分得到了 index out of range
错误,并且没有任何数据显示在TableView
.
所以我的问题是:
如何使 2 种类型的 tableViewCell 出现在 1 个单独的 TableView 中,其中数据来自 2 个不同的 API 方法调用?
最佳答案
采用 numberOfSections 方法并执行以下操作:
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return typeAArray.count
} else {
return typeBArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let typeACell = tableView.dequeueReusableCell(withIdentifier: "TypeACell", for: indexPath) as! TypeATableCell
typeACell.data = self.typeAArray[indexPath.row] //Here I get index or of range error
return typeACell
}
let typeBCell = tableView.dequeueReusableCell(withIdentifier: "TypeBCell", for: indexPath) as! TypeBTableCell
typeBCell.data = self.typeBArray[indexPath.row]
return typeBCell
}
关于ios - 如何在 1 个 TableView Swift 4 中显示 2 种类型的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48638614/