как исправить автоматическую высоту таблицы в Swift?

Я хочу отобразить вертикальное представление сбора данных в ячейке табличного представления. но когда данные впервые перезагружаются из json, высота табличного представления не изменяется автоматически. но когда табличное представление прокручивается вверх, высота табличного представления изменяется, как показано ниже.

  1. Это первое изображение появилось при перезагрузке данных из Json: введите здесь описание изображения

  2. это изображение при прокрутке таблицы вверх введите здесь описание изображения

вот мой код:

  • контроллер просмотра

    import UIKit
    
    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, reloadTable {
    
      func reloadTableData() {
        self.tableView.reloadData()
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
      }
    
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: Cell.tableView.rawValue)
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 100
    tableView.tableFooterView = UIView()
    
    tableView.register(UINib(nibName: "SecondTableViewCell", bundle: nil), forCellReuseIdentifier: "SecondTableViewCell")
    
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return 2
    }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0{
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "SecondTableViewCell", for: indexPath) as! SecondTableViewCell
        cell.name.text = "first data"
        return cell
    
    }else{
    
        let cell = tableView.dequeueReusableCell(withIdentifier: Cell.tableView.rawValue, for: indexPath) as! TableViewCell
        cell.setNeedsLayout()
        cell.layoutIfNeeded()
        return cell
      }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       if indexPath.row == 0{
          return 100
       }else {
          return UITableView.automaticDimension
       }
      }
     }
    

вот моя ячейка таблицы:

  • ТаблицаViewCell

    import UIKit
    import Alamofire
    import SwiftyJSON
    
    struct dataJSON {
       var name: String
    }
    
    protocol reloadTable {
     func reloadTableData()
    }
    
    class TableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    
    var reload: reloadTable?
    
    var dataJson : [dataJSON] = []
    
    @IBOutlet var collectionView: UICollectionView!
    
    override func awakeFromNib() {
      super.awakeFromNib()
    
      fetchData()
    
      collectionView.delegate = self
      collectionView.dataSource = self
      collectionView.isScrollEnabled = false
      collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: Cell.collView.rawValue)
    
      let collViewLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
      collViewLayout.itemSize = UICollectionViewFlowLayout.automaticSize
      layoutIfNeeded()
      setNeedsLayout()
    
      }
    
      func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
     }
    
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataJson.count
     }
    
      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.collView.rawValue, for: indexPath) as! CollectionViewCell
         cell.detail.text = dataJson[indexPath.row].name
         return cell
     }
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         return CGSize(width: collectionView.frame.size.width / 2 - 10, height:  300)
     }
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
         return 5
     }
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
     }
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
      }
    
      func fetchData(){
       Alamofire.request("https://jsonplaceholder.typicode.com/users", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON{
        (response) in
    
        switch response.result{
            case .success(let value):
                print(value)
                let json = JSON(value)
    
                let name = json["name"].stringValue
                print("nameesss: \(name)")
    
                json.array?.forEach({ (item) in
                    let data = item["name"].stringValue
                    self.dataJson.append(dataJSON(name: data))
                })
    
                self.collectionView.reloadData()
                self.reload?.reloadTableData()
    
            case .failure(let error):
                print(error)
        }
      }
    }
    
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
       self.collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width, height: 600)
       self.collectionView.layoutIfNeeded()
       return self.collectionView.collectionViewLayout.collectionViewContentSize
        }
      }
    

person pnpp    schedule 03.08.2019    source источник


Ответы (3)


Попробуйте с

 DispatchQueue.main.async { [weak self] in
        self?.tableView.reloadData()
    }
person jagdeep singh    schedule 03.08.2019
comment
я вызываю этот код внутри таблицы cellForRowAt, вторая таблица tableviewcell показывает данные. но когда я прокручиваю вниз, в последней строке indexpath первая таблица ячеек не отображается. - person pnpp; 03.08.2019

После вставки данных вы должны обновить подпредставления с помощью self.view.layoutSubviews().

person Yervand Saribekyan    schedule 03.08.2019

Установите соединения делегата и источника данных из инспектора соединений. Нажмите и перетащите выходы из инспектора подключений во владельца файла для источника данных и делегата.

введите здесь описание изображения

person Yogesh Tandel    schedule 03.08.2019