【问题标题】:Make one word of a sentence in UIButton bolded/underlined (Swift)将 UIButton 中的一个单词加粗/加下划线(Swift)
【发布时间】:2019-03-28 17:30:49
【问题描述】:

我只是想在 Swift 中以编程方式在 UIButton 中将文本句子的单个单词加粗(或下划线)。我在任何地方都找不到执行此操作的信息

【问题讨论】:

  • 你好像发现了 NSAttributedString 的问题,那是什么问题?
  • 您可以使用 setAttributedTitle 方法为您的按钮标题添加属性字符串。

标签: swift string xcode uibutton nsattributedstring


【解决方案1】:

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

    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)

【讨论】:

    【解决方案2】:

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

    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
    

    结果:

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 1970-01-01
      • 2014-08-30
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2017-01-31
      相关资源
      最近更新 更多