sizeToFit()会帮你调整文字高度。
var str : NSMutableAttributedString = NSMutableAttributedString(string: "Bla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla\nBla")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSRange(location: 13,length: 3))
button.setAttributedTitle(str, forState: UIControlState.Normal)
button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel?.textAlignment = .Center
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.sizeToFit()
button.layoutIfNeeded()
也使用您的代码:
var attrString = NSMutableAttributedString()
addNewLineToAttributedString(attrString, plainString: "Big title", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller Smaller Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller Smaller Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Big title", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Big title", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller Smaller Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller Smaller Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller Smaller Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
addNewLineToAttributedString(attrString, plainString: "Smaller Smaller Smaller text", font: UIFont.systemFontOfSize(10), preferredSize: 50, maxWidth: 100)
button.setAttributedTitle(attrString, forState: UIControlState.Normal)
button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel?.textAlignment = .Center
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.sizeToFit()
button.layoutIfNeeded()