简体   繁体   中英

how to resize the image to fit in UIImageview in a tableview cell

I am getting data from user such as Title, description, and a photo of a product and display it on posts page. I get the image, download url to firebase, then get it again with url session and here is my code for getting the image :

class ImageService {

    static let cache = NSCache<NSString, UIImage>()

    static func downloadImage(withURL url:URL, completion: @escaping (_ image:UIImage?)->()) {
        let dataTask = URLSession.shared.dataTask(with: url) { data, responseURL, error in
            var downloadedImage:UIImage?

            if let data = data {
                downloadedImage = UIImage(data: data)
            }

            if downloadedImage != nil {
                cache.setObject(downloadedImage!, forKey: url.absoluteString as NSString)
            }

            DispatchQueue.main.async {
                completion(downloadedImage)
            }

        }

        dataTask.resume()
    }

    static func getImage(withURL url:URL, completion: @escaping (_ image:UIImage?)->()) {
        if let image = cache.object(forKey: url.absoluteString as NSString) {
            completion(image)
        } else {
            downloadImage(withURL: url, completion: completion)
        }
    }

, and here is the code where I set this data:

func set(post:Post) {
    ImageService.getImage(withURL: post.imageid) { (image) in

        self.postimage.image = image
    }
    titlel.text = post.title
    usernamel.text = post.username
    desct.text = post.desc
}

, and my posts look like this when app is ran: no good , and nogood2 . also, here is a photo of my cell and they all have constraints so I don't think the problem is in this cell but still . I just want users to view Images as square normal pictures not looking tall and skinny like this.

Set the image view content mode as aspect fill and clips to bound property to true.

self.postimage.contentMode = .scaleAspectFill
self.postimage.clipsToBounds = true

使用 self.postimage.contentmode.scaleaspectfit

In your screen shot i can see that you have not provided the height constraint, thats why the images are tall. For showing square picture just provide width and height constraint on UIImageView

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