gpt4 book ai didi

swift - 在 iOS 中加载 TableView 数据时出现 TableView 部分问题

转载 作者:行者123 更新时间:2023-11-30 10:29:40 25 4
gpt4 key购买 nike

我正在尝试从 API 响应加载 TableView 中的数据,从 API 响应中我获取数组并将其传递给 TableView 委托(delegate)和数据源。我想在单个部分下显示数组的每个元素。我正在传递一个部分数组,但是当我加载数据时,它会在单个部分下显示多个元素。看起来是这样的, enter image description here

这是我显示数据的代码,

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com