用UIButton粗体/下划线(Swift)中的一个单词

问题描述 投票:-4回答:2

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

swift string xcode uibutton nsattributedstring
2个回答
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)

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

© www.soinside.com 2019 - 2024. All rights reserved.