ios - UITableViewCell、图像和纵横比

标签 ios swift uitableview

我有一个 UITableView,我需要在每个自定义单元格(使用 UIImageView)中显示不同的图像(具有不同的尺寸)。为了正确显示它们,我需要计算每个图像的纵横比并调整 UIImageView 的框架。但有一个问题。当我运行该应用程序时,它显示每个单元格的宽高比错误。然后我开始滑到 table 底部,然后又滑回顶部,好几次。每次我看到某些单元格的纵横比是正确的,而其他单元格的纵横比是错误的。是因为系统重用了原型(prototype)单元吗?

这是 tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) 中的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("EntryCell", forIndexPath: indexPath) as? PodCell

    let podcast = podList[indexPath.row]
    let title = podcast.title
    //        cell.titleLa?.text = title
    cell?.titleLabel.lineBreakMode = .ByWordWrapping
    cell?.titleLabel.numberOfLines = 0
    cell?.titleLabel.text = title
    var image = UIImage()
    if (imageCache[podcast.imageURL!] != nil) {
        image = imageCache[podcast.imageURL!]!
        cell?.imgView.image = image
    }else{
        let imgURL = NSURL(string: podcast.imageURL!)
        let request = NSURLRequest(URL: imgURL!)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)
        let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?,  error:NSError?) in
            if error == nil {
                if data != nil {
                    image = UIImage(data: data!)!
                }

                dispatch_async(dispatch_get_main_queue(), {
                    self.imageCache[podcast.imageURL!] = image
                    cell?.imgView.image = image
                })

            }else {
                print(error)
            }
        }

        task.resume()
    }
    let aspectRatio = image.size.width / image.size.height

    cell?.imgView.frame = CGRectMake((cell?.imgView.frame.origin.x)!, (cell?.imgView.frame.origin.y)!, (cell?.imgView.frame.width)!, (cell?.imgView.frame.width)! / aspectRatio)

    return cell!
}

最佳答案

您不能使用 imageView 的框架宽度作为新宽度的基础。您需要为此使用一个常量值,例如高度。

关于ios - UITableViewCell、图像和纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086127/

相关文章:

ios - 如何使用 sqlite 文件将数据预加载到 iOS 应用程序中

ios - 将拍摄的图像分配给 image view.image

ios - Swift 中的 Webview 管理

iphone - 清除 tableView 单元格缓存(或删除条目)

ios - 在 iOS 13 的 iPhone 上将纵向 View Controller 推到横向 View Controller 上

android - 如何在 React Native 中获取本地视频列表并以网格格式显示?

swift - 如何将协议(protocol)属性默认实现编码为字典

swift - 带有两个图像的 Swift 中的 UIButton

iOS Tableview 文本字段在 for 循环中获取值在 ios 7 中不起作用,但在 iOS 8 中起作用

ios - 在 objective-c 中保持 tableview 单元格上按钮的状态单击