【发布时间】: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