我正在调用一个api并从响应中获取一个数组,然后在我的表视图中填充该数组。现在我希望如果数组具有2个或更多元素,则每个元素应显示在表视图的单个部分下。本节还将有一些标题。我如何使用现有阵列做到这一点?就像我收到array [“ A”,“ B”]。现在,当应该加载表视图时,应该在第1节下显示元素“ A”,而在第2节下显示元素“ B”。我从响应中得到的数组怎么会发生这种情况?
为了每个数组元素都有一个部分,return array.count
in
func numberOfSections(在tableView中:UITableView)
将return 1
设置为
func tableView(_ tableView:UITableView,numberOfRowsInSection节:Int)
将单元格值指定为array[indexPath.section]
in
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
首先使用1个元素组成数组,首先进行array.append("");
。然后在array.count
函数中返回numberOfSections(in tableView: UITableView) -> Int
。
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return array.count
}
将您的api数据读入同一数组对象,并且完成API调用后,您可以使用tableView.reloadData()
重新加载tableView数据在titleForHeaderInSection section
return array[section]
}
如果要显示每个元素的一部分,则应在numberOfSection
中返回数组的总数。我还添加了用于在节标题中添加标题的代码。
func numberOfSections(in tableView: UITableView) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.lightGray
let headerLabel = UILabel(frame: CGRect(x: 30, y: 0, width:
tableView.bounds.size.width, height: tableView.bounds.size.height))
headerLabel.font = UIFont(name: "Verdana", size: 20)
headerLabel.textColor = UIColor.white
headerLabel.text = myArray[section]
headerLabel.sizeToFit()
headerView.addSubview(headerLabel)
return headerView
}