【问题标题】:Auto layout multiple lines label in UITableview // Swift 4.2在 UITableview // Swift 4.2 中自动布局多行标签
【发布时间】:2019-02-15 10:15:51
【问题描述】:

我写了这样的扩展来在 UITableview 中显示我的数据。但有时我的数据可能包含超过 1 行,我需要创建一些内容来显示完整内容。我怎样才能更改我的代码(如下)来做到这一点?

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 写一些东西,但我不知道,我是否正确。

请帮我解答这个问题。

【问题讨论】:

  • 看看这个答案link
  • @vpoltave 这里的标签不是由代码创建的..

标签: ios swift uitableview swift4.2


【解决方案1】:

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

  • 最初为Self Sizing Cell 设置估计高度和自动尺寸,在您的页面加载时调用以下行。

      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;
    }
    
    }
    

【讨论】:

    【解决方案2】:

    步骤 1. 在自定义表格视图单元格中添加一个完整的垂直约束链

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

    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension
    

    第三步:让标签支持多行

    textLabel.LineBreakMode = UILineBreakMode.WordWrap;
    textLabel.Lines = 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多