Reputation: 975
I need to show images from both url and uiimage in a collectionview.
The scenerio is images are coming from the api and user can add other image in the collection view.
Here is the code that I am using right now ?
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"))
}
}
Here index = 0 is used to add images from imagePicker.
Upvotes: 0
Views: 72
Reputation: 100503
You need to create a struct like this
struct Item {
var isLocal:Bool
var imageNameUrl:String
}
//
var savedPhotosArray = [Item(isLocal:true, imageNameUrl:"local.png"),Item(isLocal:false, imageNameUrl:"remoteExtension")]
//
Also don't add the images inside cellForRowAt
as cells are reusable and this glitches the UI plus memory leaks , make the imageView inside the cell xib or if programmatically and assign only in cellForRowAt
Upvotes: 1