为什么不重新加载行调整表格View Rows正确?

时间:2018-01-16 19:27:50

标签: ios swift uitableview

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 个答案:

答案 0 :(得分:1)

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宽度等于单元格宽度,最好给它tableViewWidth与viewController的视图成比例,因为这里的cellWidth尚未渲染比如tableView采用全屏宽度,然后将cellWidth设置为self.view.frame.size.width

3-不要忘记在退回单元格前放置此行

   cell.layoutIfNeeded()