UITableView показывает только одну ячейку - PullRequest
0 голосов
/ 26 сентября 2018

У меня есть UITableView с несколькими ячейками данных, но при загрузке отображается только одна ячейка.Чтобы проверить, я добавил 4 строки в массив.

class LoadingDataViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableViewDataLoading: UITableView!
    var dados = ["Vendas","Produtos","Pessoas","Animais"]

    override func viewDidLoad() {
        super.viewDidLoad()
        print("View did load")
        tableViewDataLoading.delegate = self
        tableViewDataLoading.dataSource = self
        tableViewDataLoading.layer.cornerRadius = 15.0
        tableViewDataLoading.layer.borderColor = UIColor.vorazColor.cgColor
        tableViewDataLoading.layer.borderWidth = 1.0
        tableViewDataLoading.clipsToBounds = true
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dados.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellLoadingData") as! CellDataLoading
        print("CELL: \(indexPath.row) - \(dados[indexPath.row])")
        cell.lblDado.text = dados[indexPath.row]
        cell.indicatorDado.startAnimating()
        return cell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: UITableViewAutomaticDimension))
        let label = UILabel(frame: headerView.frame)
        label.center = headerView.center
        headerView.backgroundColor = UIColor.vorazColor
        label.text = "Baixando dados..."
        label.textColor = UIColor.white
        headerView.addSubview(label)
        return headerView
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let buttonCancel = UIButton(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: UITableViewAutomaticDimension))
        buttonCancel.backgroundColor = UIColor.vorazColor
        buttonCancel.setTitle("Cancelar", for: .normal)
        buttonCancel.addTarget(self, action: #selector(cancelar), for: .touchUpInside)
        return buttonCancel
    }

    @objc func cancelar(_ sender : UIButton) {
        self.dismiss(animated: true, completion: {})
    }

}

class CellDataLoading : UITableViewCell {

    @IBOutlet weak var imgCheckDado: UIImageView!
    @IBOutlet weak var indicatorDado: UIActivityIndicatorView!
    @IBOutlet weak var lblDado: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

}

Результат:

enter image description here

Раскадровка:

enter image description here

Obs .: метка представления заголовка не отображается, и этот ViewController представлен в виде всплывающего окна.

Ответы [ 3 ]

0 голосов
/ 26 сентября 2018

Установите ограничение высоты для вашего UITableView и используйте его, как показано ниже:

@IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
    super.viewDidLoad()

    tableViewDataLoading.delegate = self
    tableViewDataLoading.dataSource = self
    tableViewDataLoading.layer.cornerRadius = 15.0
    tableViewDataLoading.layer.borderColor = UIColor.vorazColor.cgColor
    tableViewDataLoading.layer.borderWidth = 1.0
    tableViewDataLoading.clipsToBounds = true

    // For dynamic height of cells if you need that otherwise only write `heightForRowAtIndexPath`
    tableViewDataLoading.estimatedRowHeight = 88.0
    tableViewDataLoading.rowHeight = UITableViewAutomaticDimension
    tableViewDataLoading.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)

}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    tableHeightConstraint.constant = tableViewDataLoading.contentSize.height
    UIView.animate(withDuration: 0.5) {
        self.updateConstraints()
        self.layoutIfNeeded()
    }

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    // For static height
    // return 40 // Here you can set your desired height 

    // For dynamic cell height 
    return UITableViewAutomaticDimension
}
0 голосов
/ 26 сентября 2018

Хотя мне нравится подход Dhaval D больше, чем то, что я делал в недавнем проекте, в основном наблюдатель по размеру содержимого таблицы, вот что я сделал при ограниченном времени.

Представление таблицы в представлении контейнера,Контейнерное представление имеет ограничение по высоте.Представление таблицы прикреплено со всех сторон к представлению контейнера.Каждый раз, когда данные таблицы изменяются, я звоню

func updateTableSize() {

        self.tableView.layoutIfNeeded()
        var tableFrame = tableView.frame
        tableFrame.size.height = tableView.contentSize.height
        tableFrame.size.width = tableView.contentSize.width 
        tableView.frame = tableFrame
        heightConstraint.constant = tableFrame.size.height
    }
0 голосов
/ 26 сентября 2018

Здесь важна пара чисел.Извлеките скриншот из моего проекта: My Table View

Я дал этой таблице явную высоту строки, а внизу я присвоил таблице фиксированную высоту через AutoLayoutw.

Эти цифры, вероятно, не подходят для вашего проекта, но если вы отрегулируете высоту своих ячеек, я думаю, вы увидите гораздо лучшие результаты.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...