【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右端的间隔即可



posted @ 2016-02-23 14:20  云端止水  阅读(1152)  评论(0)    收藏  举报