Swift table 视图中的 Uicollection 视图

Swift Uicollection view inside a table View

我在 post 对象数组中得到了一个图像 url 数组我想在 table 视图中显示这个 post 数组并将图像显示为一个集合在 table 视图中查看。我怎样才能 enter image description here 做到这一点?我厌倦了使用 int i 作为指标,但它不起作用。

这是代码

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeTableViewCell
    cell.postsText.text = postLists[indexPath.row].postText
    i = indexPath.row
    return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (postLists[i].imageUrlList?.count)!
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! PhotosCollectionCell
        let url =  postLists[i].imageUrlList![indexPath.row]
            let imgUrl = URL(string: url)
            URLSession.shared.dataTask(with: imgUrl!, completionHandler: { (data, response, error) in
                if error != nil {
                    // if download hits an error, so lets return out
                    print(error)
                    return
                }
                // if there is no error happens...
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // in half a second...
                    cell.postPhoto.image = UIImage(data: data!)
                }
            }).resume()
    return cell
}

在你非常确定之前,永远不要强行包装可选的。 (我也可以评论,但我想添加更多不适合评论的细节,所以请原谅)

我能看到的另一件事是在 collectionView 中使用 indexPath.item 而不是 indexPath.row 两者都是一样的,但这是我一直遵循的标准。

您没有在后台线程中调用 URLSession.data 任务。始终建议这样做。我的建议是你应该使用一些第三方库,比如 SDWebIamge 这将有助于你缓存已经下载的图像。

Wy 崩溃

我看到的是崩溃,因为您的代码 postLists[i].

中的变量 i

你应该做什么

里面

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

您可以像

一样为您的 collection 视图设置标签
cell.yourCollectionViewObject.tag = indexPath.row

并替换

    let url =  postLists[i].imageUrlList![indexPath.row]

    let url =  postLists[collectionView.tag].imageUrlList![indexPath.row]

希望对您有所帮助