提供的代码专门为SO而制作,使其紧凑和清晰,在我的项目中实现的方式不同.
extension NSAttributedString { func heightWithWIDth(wIDth: CGfloat) -> CGfloat { let maxSize = CGSize(wIDth: wIDth,height: CGfloat.max) let boundingBox = self.boundingRectWithSize(maxSize,options: [.UseslineFragmentOrigin,.UsesFontLeading,.UsesDeviceMetrics],context: nil) return boundingBox.height }}extension UILabel { func getHeightWIDthGivenWIDthAndlineHeight(lineHeight: CGfloat,labelWIDth: CGfloat) -> CGfloat { let text = self.text if let text = text { let attributeString = NSMutableAttributedString(string: text) let style = NSMutableParagraphStyle() style.linespacing = lineHeight attributeString.addAttribute(NSParagraphStyleAttributename,value: style,range: NSMakeRange(0,text.characters.count)) let height = attributeString.heightWithWIDth(labelWIDth) self.attributedText = attributeString return height } return 0 }
我叫这个
let contentHeight = contentLabel.text! == "" ? 0 : contentLabel.getHeightWIDthGivenWIDthAndlineHeight(3,labelWIDth: labelWIDth)
使用普通字符串(没有间距)可以很好地工作,当我使用带有linespacing的attributesstring时如果失败则计算正确的值.
解决方法 你可以使用UILabel的sizeThatFits.例如:let text = "This is\nSome\nGreat\nText" let contentHeight = contentLabel.text! == "" ? 0 : contentLabel.getHeightWIDthGivenWIDthAndlineHeight(6,labelWIDth: labelWIDth) //returns 73.2
但只是设置
contentLabel.attributedText = contentLabel.attributedString //attributedString is same as getHeightWIDthGivenWIDthAndlineHeight let size = contentLabel.sizeThatFits(contentLabel.frame.size) //returns (w 49.5,h 99.5)
如果您需要查看以下内容,则将attributesstring的代码添加到您的扩展中:
var attributedString:NSAttributedString?{ if let text = self.text{ let attributeString = NSMutableAttributedString(string: text) let style = NSMutableParagraphStyle() style.linespacing = 6 attributeString.addAttribute(NSParagraphStyleAttributename,text.characters.count)) return attributeString } return nil }总结
以上是内存溢出为你收集整理的ios – 如何动态计算线间距的nsattributed字符串的高度全部内容,希望文章能够帮你解决ios – 如何动态计算线间距的nsattributed字符串的高度所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)