在UIButton中加粗/下划线的句子一句话(Swift)

时间:2019-03-28 17:30:50

标签: swift string xcode uibutton nsattributedstring

我只是想在Swift中以编程方式在UIButton中加粗(或加下划线)一个文本语句的单个单词。我找不到任何地方可以做的信息

2 个答案:

答案 0 :(得分:0)

在此示例中,我将UIButton的标题设置为“ Pay tribute”,并用带下划线的单词“ tribute”(以及其他各种装饰):

    let mas = NSMutableAttributedString(string: "Pay Tribute", attributes: [
        .font: UIFont(name:"GillSans-Bold", size:16)!,
        .foregroundColor: UIColor.purple,
    ])
    mas.addAttributes([
        .strokeColor: UIColor.red,
        .strokeWidth: -2,
        .underlineStyle: NSUnderlineStyle.single.rawValue
    ], range: NSMakeRange(4, mas.length-4))
    self.button.setAttributedTitle(mas, for:.normal)

答案 1 :(得分:0)

我使用这些助手来创建属性字符串:

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

结果:

partially underlined button