gpt4 book ai didi

swift - 划分 UITableView 单元格 - 重复单元格

转载 作者:行者123 更新时间:2023-11-30 10:46:07 27 4
gpt4 key购买 nike

  1. 我正在尝试根据 Firebase 数据库中的键对 Tableview 数据进行分段。

  2. 我能够根据键 (itemPreset) 正确划分所有内容。

  3. 我在将可重用单元分配到其部分时遇到问题。

  4. 单元格不断重复,每个单元格中的文本值相同。

  5. 每个单元格的行数正确,节标题正确。

这是我的代码 -

var subCategories = [SubCategoryCellInfo]()
var sectionsArray = [String]()

func querySections() -> [String] {
for selection in subCategories {
let subCategory = selection.itemPreset
sectionsArray.append(subCategory ?? "")
}
let uniqueSectionsArray = Set(sectionsArray).sorted()
return uniqueSectionsArray
}

func queryItemPreset(section:Int) -> [Int] {
var sectionItems = [Int]()
for selection in subCategories {
let itemPreset = selection.itemPreset
if itemPreset == querySections()[section] {
sectionItems.append(querySections().count)
}
}
return sectionItems
}

func numberOfSections(in tableView: UITableView) -> Int {
return querySections().count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return querySections()[section]
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering(){
return filtered.count
}
return queryItemPreset(section: section).count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let subCell = tableView.dequeueReusableCell(withIdentifier: "subCell", for: indexPath) as! SubCategoryTableViewCell
let section = queryItemPreset(section: indexPath.section)

let task = section[indexPath.row]
let sub: SubCategoryCellInfo
if isFiltering(){
sub = filtered[task]
}
else{
sub = subCategories[task]
}
subCell.nameOfLocationText.text = sub.itemPreset
return subCell
}

子类别单元格信息:

class SubCategoryCellInfo{
var itemPreset: String?

init(itemPreset:String?){
self.itemPreset = itemPreset
}
}

解决方案:我根据 itemPreset 将数组分组为多个部分,然后使用该部分

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let subCell = tableView.dequeueReusableCell(withIdentifier: "subCell", for: indexPath) as! SubCategoryTableViewCell
let groupedDictionary = Dictionary(grouping: subCategories) { (person) -> String in
return person.itemPreset ?? ""
}

var grouped = [[SubCategoryCellInfo]]()

let keys = groupedDictionary.keys.sorted()

keys.forEach { (key) in
grouped.append(groupedDictionary[key]!)
}

let task = grouped[indexPath.section]

let sub: SubCategoryCellInfo
if isFiltering(){
sub = filtered[indexPath.row]
}
else{
sub = task[indexPath.row]
}
subCell.nameOfLocationText.text = sub.itemPreset
return subCell
}

最佳答案

在您的 SubCategoryTableViewCell 中编写此代码。

override func prepareForReuse() {
super.prepareForReuse()
nameOfLocationText.text = nil
}

关于swift - 划分 UITableView 单元格 - 重复单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738718/

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