【问题标题】:set dynamic height of UITableViewCell inside UITableView using UILabel text使用 UILabel 文本在 UITableView 内设置 UITableViewCell 的动态高度
【发布时间】:2018-04-04 05:29:24
【问题描述】:

大家好,我有一个 UITableView,其中有一个 UITableViewCell,其中包含用于显示标题的 UILabel 和用于显示描述的另一个 UILabel。 UITableViewCell的Height是根据title label和description label的文字计算出来的。

以下是返回单元格高度的 UITableView 方法,其中我根据名称和描述字段的文本计算单元格的高度。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var height: CGFloat = 60

    if empCornerSC.selectedSegmentIndex == 0{

        let kra = kraList[indexPath.row]
        let maxSize = CGSize(width: 200 , height: 1000)
        let nameLabelSize = rectForText(text: kra.kraName!, font: 16, maxSize: maxSize)
        let descriptionLabel = rectForText(text: kra.kraDescription!, font: 14, maxSize: maxSize)
        height = nameLabelSize.height + descriptionLabel.height
        height = height + 20
    }
    return height
}

根据文字和字体计算高度的方法,这个方法是从 Youtube Lets Build That App 那里得到的

func rectForText(text: String, font: CGFloat, maxSize: CGSize) -> CGRect {

    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    return NSString(string: text).boundingRect(with: maxSize, options: options, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: font)], context: nil)
}

我能够为我的 UITableViewCell 获取动态大小,但检查screenshot 不一致 正如您在图像中看到的,如果标签和描述文本很大,则单元格高度很大,而当 lebel 的内容较少时,大小也较小。我想要与内容大小相关的单元格高度。请帮我。提前谢谢你。

【问题讨论】:

    标签: uitableview uilabel swift4


    【解决方案1】:

    let maxSize = CGSize(width: 200 , height: 1000) 更改为let maxSize = CGSize(width: labelWidth , height: 1000)

    labelWidth 应该是特定标签允许的最大宽度。您可以使用 [[UIScreen mainScreen] bounds].size.width - [XX](40/50 etc. 根据您的约束条件) 之类的东西。在这种情况下,200 似乎非常少,如随附的屏幕截图所示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2010-11-03
      相关资源
      最近更新 更多