【问题标题】:Swift Uicollection view inside a table View表视图中的 Swift Uicollectionview
【发布时间】:2019-02-09 06:56:30
【问题描述】:

我在帖子对象数组中获得了一个图像 url 数组我想在表格视图中显示此帖子数组并将图像显示为表格视图中的集合视图。我怎样才能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
}

【问题讨论】:

标签: swift tableview collectionview


【解决方案1】:

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

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

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

Wy 崩溃

我看到的是由于代码postLists[i]. 中的变量i 而导致的崩溃

你应该怎么做

里面

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

您可以将标签设置为您的收藏视图,例如

cell.yourCollectionViewObject.tag = indexPath.row

替换

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

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多