简体   繁体   English

如何调整图像大小以适应表视图单元格中的 UIImageview

[英]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 :我获取图像,将 url 下载到 firebase,然后使用 url 会话再次获取它,这是我获取图像的代码:

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 . ,当应用程序运行时,我的帖子看起来像这样: no goodnogood2 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.将图像视图内容模式设置为纵横填充并将剪辑绑定属性设置为 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为了显示方形图片,只需在 UIImageView 上提供宽度和高度约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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