【问题标题】:Dynamic collectionView with UIimageView height具有 UIimageView 高度的动态 collectionView
【发布时间】:2017-05-17 17:05:55
【问题描述】:

我想使用 swift 3 在 collectionView 中显示像 https://www.pinterest.com 这样的图像。因为图像来自后端,只有 URL 而不是图像大小。所以我想根据图像的高度动态显示单元格。

我正在做的是,

        let url = self.myArray[indexPath.row].image
        let data = NSData(contentsOf:URL(string: url)!)
        var photo = UIImage()

        if (data?.length)! > 0 {
            photo = UIImage(data:data! as Data)!
        }

        let boundingRect =  CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
        let rect  = AVMakeRect(aspectRatio: photo.size, insideRect: boundingRect)

        return rect.size.height

它返回我的高度。

问题是:图像是高清的,大小高达 3MB。

        let data = NSData(contentsOf:URL(string: url)!)

需要很多时间,因为我有 20 到 30 张图片。

有没有办法在另一个线程而不是主线程上下载图像,所以下载图像将在后台继续,

或者任何人都有更好的解决方案来计算来自 URL 的图像高度。

PS:我已经关注 https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest 的 customLayout。

提前致谢。

【问题讨论】:

    标签: swift3 uiimageview uicollectionview flowlayout


    【解决方案1】:

    您应该查看Alamofire。它使用 Promise 异步发出请求,而不会阻塞 UI 线程。你的代码看起来像这样

    Alamofire.request(URL_STRING, method: .get, parameters: nil, encoding: URLEncoding.default, headers: getHeaders())
                    .validate()
                    .responseImage(completionHandler: {response in
                        switch response.result {
                        case .success:
                            //The image will be stored in response.data in NSData format
                            break
                        case .failure(let error):
                            //Handle errors over here
                            break
                        }
                    })
    

    【讨论】:

    • 让我试一试
    • 我想在返回方法 func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:NSIndexPath, withWidth:CGFloat) -> CGFloat 中调用它
    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    相关资源
    最近更新 更多