NSAttributedString无法正确显示

时间:2016-02-04 09:04:19

标签: ios swift uilabel

我希望我的UILabel能够将长名称分成两行并添加连字符。目前我的代码是这样的:

let usernameX = profilePhoto.frame.size.width+horizontalMargin
let username = UILabel(frame: CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: self.frame.size.width-usernameX-horizontalMargin, height: 42))
username.adjustsFontSizeToFitWidth = true
username.font = UIFont(name: "SFUIDisplay-Regular", size: 20)
username.minimumScaleFactor = 0.8
username.numberOfLines = 2
username.translatesAutoresizingMaskIntoConstraints = false
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 0.5
let attributedString = NSMutableAttributedString(string: "Areallylongname", attributes: [NSParagraphStyleAttributeName: paragraphStyle])

但是标签只显示"Areally-"。我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以重新检查标签的超级视图的高度。

答案 1 :(得分:0)

将42固定为高度不是正确的方法。您可以动态计算所需标签的高度并进行分配。你可以按照以下方式去做。

let attributedString = NSMutableAttributedString(string: "Areallylongname", attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName : UIFont(name: "SFUIDisplay-Regular", size: 20)])
var newFrame = attributedString.boundingRectWithSize(CGSizeMake(username.frame.size.width, 9999), options: NSStringDrawingOptions.UsesLineFragmentOrigin , context: nil)
newFrame.origin.x = username.frame.origin.x
newFrame.origin.y = username.frame.origin.y

您可以在viewDidLayoutSubviews

中设置新框架