使NSMutableAttributedString和sizeThatFits一起工作

时间:2016-02-04 13:53:33

标签: ios uilabel nsattributedstring

我遇到了使NSMutableAttributedString和sizeThatFits协同工作的问题。我有一个UILabel,它必须不比常量self.frame.size.width-usernameX-horizontalMargin宽。我希望UILabel如果适合就是一行,如果它太长则需要两行带连字符。目前我正在使用此代码:

let usernameX = profilePhoto.frame.size.width+horizontalMargin
let username = UILabel()
username.adjustsFontSizeToFitWidth = false
username.font = UIFont(name: "SFUIDisplay-Regular", size: 18)
username.numberOfLines = 0
username.translatesAutoresizingMaskIntoConstraints = false

//Set hyphenation
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 0.2
username.attributedText = NSMutableAttributedString(string: displayName, attributes: [NSParagraphStyleAttributeName: paragraphStyle])
let maxSize = CGSize(width: self.frame.size.width-usernameX-horizontalMargin, height: CGFloat.max)
let requiredSize = username.sizeThatFits(maxSize)
username.frame = CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: requiredSize.width, height: requiredSize.height)

self.addSubview(username)

目前,文本只显示带有连字符的一行。第二行没有显示。我在这里做错了什么想法?我已经尝试将行数设置为2,这没有任何区别。任何指针都会非常感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

您还需要在属性中包含您的字体,否则它将默认喜欢属性文本。你能尝试一下吗?

let attributedString = NSMutableAttributedString(string: displayName, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName : UIFont(name: "SFUIDisplay-Regular", size: 18)])
var newFrame = attributedString.boundingRectWithSize(CGSizeMake(self.frame.size.width-usernameX-horizontalMargin, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin , context: nil)
username.frame = CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: newFrame.size.width, height: newFrame.size.height)

如果您想使用sizeThatFits,可以使用以下

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 0.2
username.attributedText = NSMutableAttributedString(string: displayName, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName : UIFont(name: "SFUIDisplay-Regular", size: 18)])
let maxSize = CGSize(width: self.frame.size.width-usernameX-horizontalMargin, height: CGFloat.max)
let requiredSize = username.sizeThatFits(maxSize)
username.frame = CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: requiredSize.width, height: requiredSize.height)

self.addSubview(username)