如何快速在集合视图中同时显示url和uiimage中的图像?

时间:2018-07-08 15:37:34

标签: swift uicollectionview

我需要在collectionview中显示来自url和uiimage的图像。

场景是图像来自api,用户可以在集合视图中添加其他图像。

这是我现在正在使用的代码?

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return savedPhotosArray.count + 1

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = checkOutCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)as! CheckOutCollectionViewCell

    if indexPath.row == 0{
        let img = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height))
        img.layer.cornerRadius = 10
        cell.addSubview(img)
        img.image = #imageLiteral(resourceName: "plus")
        img.backgroundColor = blackThemeColor
    }else{
        let img2 = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height))
        img2.layer.cornerRadius = 10
        img2.clipsToBounds = true
        cell.addSubview(img2)

        if let image = savedPhotosArray[indexPath.row - 1] as? String
        {
            let imageStr = basePhotoUrl + image
            print (imageStr)

            let imageUrl = URL(string: imageStr)
            img2.sd_setImage(with: imageUrl , placeholderImage: #imageLiteral(resourceName: "car-placeholder"))
        }

}

此处索引= 0用于从imagePicker添加图像。

1 个答案:

答案 0 :(得分:1)

您需要创建一个这样的结构

struct Item {

    var isLocal:Bool
    var imageNameUrl:String

}

//

var savedPhotosArray  = [Item(isLocal:true, imageNameUrl:"local.png"),Item(isLocal:false, imageNameUrl:"remoteExtension")]

//

也不要在cellForRowAt内添加图像,因为单元格是可重用的,这会导致UI加内存泄漏,使imageView出现在单元格xib内,或者以编程方式仅在cellForRowAt内分配