作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试从 API 响应加载 TableView 中的数据,从 API 响应中我获取数组并将其传递给 TableView 委托(delegate)和数据源。我想在单个部分下显示数组的每个元素。我正在传递一个部分数组,但是当我加载数据时,它会在单个部分下显示多个元素。看起来是这样的,
这是我显示数据的代码,
func numberOfSections(in tableView: UITableView) -> Int {
return headerArray.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let bgView = UIView()
bgView.backgroundColor = #colorLiteral(red: 0.3221348226, green: 0.6953448653, blue: 0.9635410905, alpha: 1)
bgView.layer.cornerRadius = 2.0
let titleLbl = UILabel()
titleLbl.frame = CGRect(x: 10, y: 10, width: 150, height: 20)
titleLbl.text = headerArray[section]
titleLbl.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
titleLbl.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
bgView.addSubview(titleLbl)
return bgView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if vcType == "SellerInProcess"
{
return propertyObject?.owners?.count ?? 0
}
else
{
return ownersList?.count ?? 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let owners = ownerArray[indexPath.row]
if owners.userType != nil && owners.userType == Identity.OWNER {
let cell : OwnerListTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "OwnerListTableViewCell", for: indexPath) as? OwnerListTableViewCell
let ownerData = ownersList![indexPath.row]
cell.ownerData = ownerData as? OwnerModel
return cell
}
}
对于我这样制作的部分数组,
var i = 1
self?.headerArray.removeAll()
for _ in self?.ownersList ?? []
{
let index = i + 0
i += 1
self?.print(i,index)
let sectionString = "Owner \(index)"
self?.headerArray.append(sectionString)
}
如何在单个部分下显示每个元素?
最佳答案
如果您只想在每个部分中包含一个单元格,则需要在 numberOfRowsInSection
方法中返回 1 或 0(对于空部分)。您还需要修改 cellForRow
部分并使用 indexPath.section
作为数组索引来获取此部分的元素。
此外,我不会准备 headerArray
,因为您可以在 viewForHeaderInSection
内生成字符串,因为您将获得 section
变量并且可以执行以下操作像这样的东西: let headerTitle = "Owner\(section + 1)"
+1 因为索引是从零开始计算的。
关于swift - 在 iOS 中加载 TableView 数据时出现 TableView 部分问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59410681/
我是一名优秀的程序员,十分优秀!