UILabel自适应高度

来源:互联网 发布:淘宝迅雷白金会员 编辑:程序博客网 时间:2024/06/11 04:33

最近需要写一个类似于社交网络分享信息的功能,其中,用于展示文字信息的UILabel需要根据文字的长度来自适应高度。如图所示:
img1
我写了一个这样的cell,就是根据文字来更新UILabel的高度:
从xib里向.swift文件里拖入UILabel的高度:
img2

// MARK: - 内容label的高度    @IBOutlet weak var labelHeight: NSLayoutConstraint!

然后在设置UILabel的属性的方法里添加以下代码:

// MARK: - 使UILabel里的文字换行self.contentLabel.lineBreakMode = NSLineBreakMode.byCharWrappingself.contentLabel.numberOfLines = 0self.contentLabel.text = content// MARK: - 使UILabel根据文字内容自适应高度let contentLabelText: NSString = self.contentLabel.text! as NSStringlet attributes = [NSFontAttributeName: self.contentLabel.font!]let options = NSStringDrawingOptions.usesLineFragmentOriginlet contentLabelSize = contentLabelText.boundingRect(with: CGSize(width: UIScreen.main.bounds.width, height: 0), options: options, attributes: attributes, context: nil)self.labelHeight.constant = contentLabelSize.height// MARK: - 刷新collection获取最新高度self.picturesCollectionView.reloadData()let contentSize = self.picturesCollectionView.collectionViewLayout.collectionViewContentSizecollectionViewHeight.constant = contentSize.height

更新另一种简单的方法:

self.titleLabel.text = "热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡热水卡"self.titleLabel.numberOfLines = 0self.titleLabel.sizeToFit()

这种方法使用的时候,原本设置好的UILabel的frame的height将失效。

0 0