【问题标题】:cell text label not centered after changing the cell height更改单元格高度后单元格文本标签未居中
【发布时间】:2019-09-12 20:27:36
【问题描述】:

我有一个 value1 类型的单元格,因为我的一些详细标签文本太长并且被截断,所以我正在更新单元格高度以适合文本。

但是更新高度后,我的文本标签位于左上角,而不是垂直位于中间。像这样:

==================         =====================
label                =>    label
==================         

                           =====================

有人知道如何解决这个问题吗?

编辑

改变高度的代码:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var rowHeight=44.0
    var numOfLines = 1;
    if let cell = tableView.cellForRow(at: indexPath),let label = cell.detailTextLabel, let size = label.text?.size(withAttributes: [NSAttributedString.Key.font:label.font]){
        let labelWidth = label.frame.width
        label.textAlignment = .left
        while(Int(size.width) > Int(labelWidth) * numOfLines){
            rowHeight+=20;
            numOfLines+=1
        }
        //becuase it was rounded down as int
        numOfLines+=1
        print("number of lines \(numOfLines)")
        label.numberOfLines = numOfLines
        label.lineBreakMode = .byCharWrapping
    }
    return CGFloat(rowHeight)
}

【问题讨论】:

  • 展示你如何设置约束
  • @Sh_Khan 更新
  • 不要获取heightForRowAt中的单元格。没有必要。从数据模型而不是单元格中获取文本。
  • @rmaddy 我需要该单元格,因为我需要该单元格的标签尺寸来更新高度。

标签: ios swift uitableview uilabel


【解决方案1】:

@Anna,我相信您的问题可以通过 UITableViewAutomaticDimension 解决。

只要确保标签的numberOfLines 设置为0 并且heightForRowAtIndexPath 委托方法应该返回UITableViewAutomaticDimension 并且不要忘记为标签添加右、左、上和下约束.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return UITableViewAutomaticDimension
 } 

请找到链接以获取更多参考: UITableViewAutomaticDimension

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 2017-01-30
相关资源
最近更新 更多