Я использую эти помощники для создания приписанных строк:
extension NSAttributedString {
typealias Style = [Key: Any]
}
extension Array where Element == NSAttributedString {
func joined() -> NSAttributedString {
let mutable = NSMutableAttributedString()
for element in self {
mutable.append(element)
}
return mutable.copy() as! NSAttributedString
}
}
extension String {
func styled(_ style: NSAttributedString.Style = [:]) -> NSAttributedString {
return NSAttributedString(string: self, attributes: style)
}
}
Вот как их использовать для создания кнопки с частично подчеркнутым заголовком:
let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
rootView.backgroundColor = .white
let button = UIButton(type: .roundedRect)
let title = [
"Hello, ".styled(),
"world!".styled([.underlineStyle: NSUnderlineStyle.single.rawValue])
].joined()
button.setAttributedTitle(title, for: .normal)
button.sizeToFit()
button.center = CGPoint(x: 100, y: 50)
rootView.addSubview(button)
import PlaygroundSupport
PlaygroundPage.current.liveView = rootView
Результат: