tableViews的行高大小不正确,我正在尝试根据下面的宽高比来调整tableViews的行高大小,这是我目前为止为cellForRowAtheightForRowAt编写的代码。此外,有些图像被下载了两次,而其他图像根本没有下载。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Reuse", for: indexPath) as! TableViewCell

    let downloadURL = URL(string: self.imageURLS[indexPath.row])

    if let image = imageCache.object(forKey: self.imageURLS[indexPath.row] as NSString)
    {
        cell.cellImageView.image = image
    }
    else{
    URLSession.shared.dataTask(with: downloadURL!, completionHandler: {(data,response,error) in

        if error != nil {
            print(error!)
            return
        }
        let downloadedImage = UIImage(data:data!)
        let aspect = CGFloat((downloadedImage?.size.width)!/(downloadedImage?.size.height)!)
        self.imageCache.setObject(downloadedImage!, forKey: self.imageURLS[indexPath.row] as NSString)
        DispatchQueue.main.async {
        cell.cellImageView.image = downloadedImage
        cell.cellImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width/aspect)
            cell.imageView?.contentMode = .scaleAspectFit
          //  cell.cellImageView.heightAnchor.constraint(equalTo: cell.cellImageView.widthAnchor, multiplier: aspect)
            tableView.reloadRows(at: [indexPath], with: .top)
            }
        }).resume()
    }

    return cell
}



override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

基于建议更新代码
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Reuse", for: indexPath) as! TableViewCell

    let downloadURL = URL(string: self.imageURLS[indexPath.row])

    if let image = imageCache.object(forKey: self.imageURLS[indexPath.row] as NSString)
    {
        cell.cellImageView.image = image
    }
    else{
    URLSession.shared.dataTask(with: downloadURL!, completionHandler: {(data,response,error) in

        if error != nil {
            print(error!)
            return
        }
        let downloadedImage = UIImage(data:data!)
        let aspect = CGFloat((downloadedImage?.size.width)!/(downloadedImage?.size.height)!)
        self.imageCache.setObject(downloadedImage!, forKey: self.imageURLS[indexPath.row] as NSString)
        DispatchQueue.main.async {
        cell.cellImageView.image = downloadedImage
            cell.cellImageView.heightAnchor.constraint(equalTo: cell.cellImageView.widthAnchor, multiplier: aspect).isActive = true
            cell.imageHeight.constant = (cell.bounds.width * (cell.cellImageView.image?.size.height)!)/(cell.cellImageView.image?.size.width)!
            cell.layoutIfNeeded()
            tableView.reloadRows(at: [indexPath], with: .top)
            }
        }).resume()
    }

    return cell
}



override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    print("UITableViewAutomaticDimension: \(UITableViewAutomaticDimension)")
    return UITableViewAutomaticDimension
}
}

最佳答案

1-尝试保存图像,然后重新加载表

  NSString *getImagePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg",n1.Id]];

    if([[NSFileManager defaultManager] fileExistsAtPath:getImagePath])
    {
        UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
        cell.leftImageV.image =img;
        [cell.activity stopAnimating];
        cell.activity.hidden=YES;
    }
    else
    {

        [cell.activity startAnimating];
         cell.activity.hidden=NO;

        cell.leftImageV.image = nil;

        NSLog(@"xdasdxsadxa %@",n1.mainImgStr);

        dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

        dispatch_async(concurrentQueue, ^{
            __block NSData * imageData  = nil;
            dispatch_sync(concurrentQueue, ^{

                imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:n1.mainImgStr]];

                //Add the file name
                [imageData writeToFile:getImagePath atomically:YES]; //Write the file

            });

            dispatch_sync(dispatch_get_main_queue(), ^{

                if(imageData)
                {
                    [self.tableView reloadData];

                }
            });
        });
    }

2-关于纵横比,将imageView的高度拖动为IBOutlet
在cellForRowAt做这个
   cell.imageHeightCon.constant = (cellWidth*imageRealHeight)/imageRealWidth

注意:这里我假设imageview width等于单元格宽度,最好将tableViewWidth与viewController的视图成比例,因为cellWidth还没有呈现,比如tableView采用全屏宽度,然后将cellWidth设置为self.view.frame.size.width
3-不要忘了把这一行放在返回单元格之前
   cell.layoutIfNeeded()

10-06 14:01