Swift 中有两个数组的 MultipleCollectionViews

MultipleCollectionViews with two arrays in Swift

目前我正在解析来自 Json 的数据并将其保存在本地。然后我用第一个数组中的数据填充 CollectionView。但现在我想添加第二个 CollectionView,它取决于第一个 CollectionView 的选择。

我的Json结构:

struct Posts: Codable {
    let id: Int
    let name: String
    let ImageURL: String
    let Rarity: [PostType]
}

struct PostType: Codable {
    let type: String
    let test: int
    let test2: String
}

我尝试了什么:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.PostsCollectionView{
    return getPostsFromDisk().count
    }else
    {
        return feedWrapper.count //not working

    }

}
var feedWrapper:[PostType] = []

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.PostsCollectionView{
    let cell = PostsCollectionView.dequeueReusableCell(withReuseIdentifier: "PostsUICollectionViewCell", for: indexPath) as! PostsUICollectionViewCell

    cell.PostsNameLbl.text = getPostsFromDisk()[indexPath.row].name
    cell.PostsImage.sd_setImage(with: URL(string: getPostsFromDisk()[indexPath.row].ImageURL))

        return cell
    }else
    {
        let cell = PostsRareCollectionView.dequeueReusableCell(withReuseIdentifier: "PostsRareCollectionViewCell", for: indexPath) as! PostsRareCollectionViewCell

        if(feedWrapper[indexPath.row].type == "normal"){
            cell.PostsRareImageView.image = [imageFromAssets]
        }

        return cell
    }


}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    PostsName.text = getPostsFromDisk()[indexPath.row].name

    //thougt i could save the selecte array to feedWrapper but its not working like expected
    feedWrapper = getPostsFromDisk()[indexPath.row].Rarity


}

我认为我的 var feedWrapper 一开始没有填满,但我不确定该怎么做

我希望有人能帮我解决这个问题

提前致谢

您需要重新加载 collectionView。您可以使用此代码:

didset 声明你的变量(假设你的数组在视图控制器中)

    var feedWrapper:[PostType] = [] {
    didSet {
         self.yourCollectionView.reloadData()
     }
    }