繁体   English   中英

UITableViewCell,图像和长宽比

[英]UITableViewCell, images and aspect ratio

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

这是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框架的宽度用作新宽度的基础。 您需要为此使用一个恒定值,也许是高度。

Yup单元被重用,最好将这种方法的整个代码发布出来,尤其是在创建单元的地方。

根据我的收集,是您尝试从缓存加载图像,如果不存在,则从Internet加载图像。 此解决方案的问题是,当您没有图像时,您将以存根的长宽比显示一些存根图像。 实际图像加载完成后,将直接放置在UIImageView ,而无需调整大小。

有两种方法可以做到这一点。 一种是具有恒定的图像尺寸。 另一种是在新图像加载完成后重新加载单元。

暂无
暂无

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

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