简体   繁体   中英

collectionView Images: Change Height Dynamically in Swift

In the scenario, images are downloading and showing into collectionview , and it is working fine, but images are displaying in different ways. I have shown all the images and they all possess the same height and the same width. If an image is small then it will take the default image height and width. I have shown all the images are same height and width displayed in properly.

在此处输入图片说明

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "storeCell", for: indexPath) as? EShoppingStoreCollectionViewCell
        cell?.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        cell?.layer.borderWidth = 0.5

        let urlData = storeDictionary?[indexPath.item]["logo"] as? String
        cell?.storeImageView.contentMode = UIViewContentMode.scaleAspectFit
        cell?.storeImageView.clipsToBounds = true
        let frame = CGRect(x: (cell?.storeImageView.frame.width)!/2 - 30, y: (cell?.storeImageView.frame.height)! - 30, width: 60, height: 60)

        if urlData != nil {
            let url = URL(string: urlData!)
            cell?.storeImageView.sd_setImage(with: url!, placeholderImage: UIImage(named:""), options: [SDWebImageOptions.continueInBackground, SDWebImageOptions.lowPriority, SDWebImageOptions.refreshCached, SDWebImageOptions.handleCookies, SDWebImageOptions.retryFailed]) { (image, error, cacheType, url) in
                if error != nil {
                    print("Failed: \(String(describing: error))")
                } else {
                    print("Success")
                }
            }
        }
    return cell!
}

how can I set all images same size

The size of image is not in your hand. It is what it is received from the API. So it is better to use a right resolution image with contentMode set to scaleAspectFit instead of stretching it.

Still if you want same size in the display, try changing contentMode of imageView to scaleAspectFill or scaleToFill

cell?.storeImageView.contentMode = UIViewContentMode.scaleAspectFill

This will definitely stretch the images but all the images that you see in display will cover the size of imageView .

You can also choose another way that'll make your UI look better - set a backgroundColor of imageView and set its contentMode to scaleAspectFit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM