多行 NSAttributed 字符串作为 UIButton 标题

Multiline NSAttributed String as UIButton Title

我的问题在理论上与这个类似:iOS NSAttributedString on UIButton

我希望将按钮的标题读作:

"带下划线的字符串

一些文字

这需要在 swift 中完成并且 100% 以编程方式完成。

我试图通过使用 NSMutableAttributedString 创建带下划线的部分然后将其附加到其他文本(以换行符开头)来实现这一点。但是,这给了我错误 "Cannot assign value of type 'Void' ('aka'()') to type 'NSMutableAttributedString"

代码如下:

var patientName = NSMutableAttributedString(string:"Patient Name", attributes: underlineAttributes)
var clickforinfomessage = NSMutableAttributedString(string: "\nclick for patient info")
clickforinfomessage = clickforinfomessage.appendAttributedString(patientName)
startVisitButton.setAttributedTitle(clickforinfomessage, forState: .Normal)

只需设置按钮标题标签的行数

let attrTet = NSMutableAttributedString(string: "Test is \ne next line.", attributes: nil)
testButton.titleLabel?.numberOfLines = 0
testButton.setTitle(attrTet.string, forState: .Normal)

代码视图:

输出:

你可以这样做:

let dict1 = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]

let attString = NSMutableAttributedString()
attString.appendAttributedString(NSAttributedString(string: "Patient Name\n", attributes: dict1))
attString.appendAttributedString(NSAttributedString(string: "click for patient info", attributes: nil))
startVisitButton.setAttributedTitle(attString, forState: .Normal)
startVisitButton.titleLabel?.numberOfLines = 0
startVisitButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping

结果将是: