【问题标题】:Problem iterating through an array, which has been grouped遍历已分组的数组时出现问题
【发布时间】:2019-04-03 06:16:18
【问题描述】:

我有一个 tableViewCell,它包含一个可以显示一些单元格的 collectionView。我已将数据链接到 firebase,它将显示在此 tableView 中。

我目前面临一个问题,我使用新的 Dictionary 分组功能(我在 TableViewCell 中做了)对某个结构的数组进行了分组。

完成此操作后,我尝试在 collectionView 单元格中的 cellforItemAtIndexPath 中迭代。

我注意到的是,当我运行代码时,我的单元格会显示迭代的后半部分,即最后一段。

请在下面找到我的 tableView 代码:

struct WebsiteStruct{
var title: String
var description: String
var banner: String
var link: String
}

var siteInfos: [WebsiteStruct] = []
var siteSections: [String] = []

class Websites: UIViewController, UITableViewDelegate, UITableViewDataSource{

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()

    let websitesRef = Database.database().reference().child("Schools").child(Variables.schoolName).child("Websites")

    websitesRef.observe(.value, with: { snapshot in
        for site in snapshot.children {
            if let siteSnapshot = site as? DataSnapshot{
                let siteInfo = siteSnapshot.value as? NSDictionary
                siteInfos.append(WebsiteStruct(title: siteInfo?.value(forKey: "title") as! String, description: siteInfo?.value(forKey: "description") as! String, banner: siteInfo?.value(forKey: "banner") as! String, link: siteInfo?.value(forKey: "link") as! String))
            }
        }
        self.tableView.reloadData()
    })
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    for website in siteInfos{
        let section = website.description
        if !siteSections.contains(section){
            siteSections.append(section)
        }
    }
    return siteSections.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "websiteSectionCell") as! WebsiteSectionCell
    cell.displayContent(sectionTitle: siteSections[indexPath.row], indexPath: indexPath.row)
    return cell
}
}

这是我的 collectionViewCell 的代码:

class WebsiteSectionCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource{

@IBOutlet weak var websiteCornerView: UIView!
@IBOutlet weak var Title: UILabel!
@IBOutlet weak var websiteCollectionView: UICollectionView!

var currentIndexPath: Int = 0
let groupedSites = Dictionary(grouping: siteInfos, by: { $0.description })

func displayContent(sectionTitle: String, indexPath: Int){
    websiteCornerView.layer.cornerRadius = Variables.cornerRadius
    websiteCornerView.layer.masksToBounds = true

    Title.text = sectionTitle
    currentIndexPath = indexPath
}

override func awakeFromNib() {
    super.awakeFromNib()
    websiteCollectionView.dataSource = self as UICollectionViewDataSource
    websiteCollectionView.delegate = self as UICollectionViewDelegate
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    //Set selected
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    for site in groupedSites[siteSections[currentIndexPath]]!{
        print(site.title)
    }
    print(groupedSites[siteSections[currentIndexPath]]!)
    return groupedSites[siteSections[currentIndexPath]]!.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! WebsiteCell
    for site in groupedSites[siteSections[currentIndexPath]]!{
        cell.displayContent(title: site.title, banner: Variables.schoolBanner!)
        print(indexPath)
    }
    return cell
}
}

这是外观的屏幕截图。

我不知道它是否有某种关联,但 collectionView cellForItemAt indexPath 函数似乎运行代码 4 次,而它本应只运行 2 次。

一些重要信息:我的所有数据都已正确组合在一起,当我在控制台中打印时,会显示正确的数组:

[EEB3App.WebsiteStruct(title: "Site 1", description: "School", banner: "/", link: "/"), EEB3App.WebsiteStruct(title: "Site 2", description: "School", banner: "/", link: "/")]

[EEB3App.WebsiteStruct(title: "Site 3", description: "Utility", banner: "/", link: "/"), EEB3App.WebsiteStruct(title: "Site 4", description: "Utility", banner: "/", link: "/")]

【问题讨论】:

  • 你不能在numberOfRowsInSection 中有一个循环,因为该函数将被多次调用,导致siteSections 有重复。您应该设置siteSections 用于检索数据。
  • 感谢您的评论。 siteSections 不能有重复,因为我编码它的方式。如果要追加的值在 siteSections 中不存在,它只会追加到 siteSections
  • 您能否显示您的单元格的代码,尤其是cell.displayContentprepareForReuse

标签: ios uitableview uicollectionview swift4 xcode10


【解决方案1】:

首先,您的代码很难阅读。我建议至少将结构重构为不同的文件。

另一件事是您需要检查这行特定的代码。它不是一个有序数组,可能会返回相同的值给您。

let groupedSites = Dictionary(grouping: siteInfos, by: { $0.description })

这应该在 WebsitesViewController 中声明和使用,而不是在单元格中执行逻辑。你可以用这个替换siteSections的数组和siteInfos的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多