【iOS】swift-文字宽度的计算

时间:2023-03-09 17:36:17
【iOS】swift-文字宽度的计算

【iOS】swift-文字宽度的计算

如图所示,需要sectionView的标题宽度可以动态变化

举例说明:

只需在tableView的代理方法

func tableView(tableView:
UITableView, viewForHeaderInSection section:
Int) -> UIView? {

let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(sectionViewId)
as! NameListSectionView

view.updateLabel(“xxxxxxxxxx”)

return view

}

然后在sectionView文件里

func updateLabel(labelText:
String){

label.text = labelText

let statusLabelSize = labelText.sizeWithAttributes([NSFontAttributeName
: UIFont.systemFontOfSize(13)])

labelWidthConstraint.constant = statusLabelSize.width
+ 4

layoutIfNeeded()

}

labelWidthConstraint为Xib文件里 label宽度的约束,右边横线的左边设置为到label右端的间隔即可