在UITableview // Swift 4.2中自动布局多行标签

问题描述 投票:-1回答:2

我写了这样的扩展来在UITableview中显示我的数据。但有时我的数据可能包含多行,我需要创建一些内容来显示完整内容。我怎么能改变我的代码(下面)来做呢?

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    // Define no of rows in your tableView
    func tableView(_ chatHistoryTable: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messagesData.count
    }

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

        cell.textLabel!.text = messagesData[indexPath.row]
        cell.textLabel!.textAlignment = .right

        return cell;
    }

}

我认为我也应该为UITableViewCell写一些东西,但我不知道,我是否正确。

请帮我解决这个问题。

ios swift uitableview swift4.2
2个回答
0
投票

在这里你需要遵循两个变化。

  • 最初设置Self Sizing Cell的估计高度和auntomaticdimension,在您的页面上加载调用以下行。 tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableView.automaticDimension 例如 @IBOutlet weak var yourTableviewName: UITableView!{ didSet{ yourTableviewName.tableFooterView = UIView() yourTableviewName.estimatedRowHeight = 44.0 yourTableviewName.rowHeight = UITableView.automaticDimension } }
  • 你的自动换行的辅助词和你的标签的numberOfLines。按照您的cellforRow方法的以下行 func tableView(_ chatHistoryTable: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = chatHistoryTable.dequeueReusableCell(withIdentifier: "userMessage")! as UITableViewCell cell.textLabel!.numberOfLines = 0 cell.textLabel!.lineBreakMode = .byWordWrapping cell.textLabel!.text = messagesData[indexPath.row] cell.textLabel!.textAlignment = .right return cell; } }

0
投票

步骤1.在Custom Table View Cell中添加一系列不间断的垂直约束

步骤2.设置单元估计高度

tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension

第3步:使标签支持多行

textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;
© www.soinside.com 2019 - 2024. All rights reserved.