Swift下划线按钮文字


78

我有UIButton。在界面构建器中,我将其标题设置为“已归因”。如何在Swift的代码中使标题加下划线?

@IBOutlet weak var myBtn: UIButton!

我创建了一个在此按钮的touchUpInside事件上调用的函数:

var attributedString = NSMutableAttributedString(string:"new text")
    var attrs = [
        NSFontAttributeName : UIFont.systemFontOfSize(19.0),
        NSForegroundColorAttributeName : UIColor.redColor()
    ]
    var gString = NSMutableAttributedString(string:"g", attributes:attrs)
    attributedString.appendAttributedString(gString)

    myBtn.titleLabel?.attributedText = attributedString;

但是仍然没有结果。我还需要知道如何访问下划线属性。文字,大小和颜色保持不变。


谢谢,但由于某种原因而不工作,我还需要了解下划线属性。
moonvader

Answers:


90

在这里,您只需对其进行测试。(至少在xCode 7 Beta中有效)

@IBOutlet weak var yourButton: UIButton!

var attrs = [
NSFontAttributeName : UIFont.systemFontOfSize(19.0),
NSForegroundColorAttributeName : UIColor.redColor(),
NSUnderlineStyleAttributeName : 1]

var attributedString = NSMutableAttributedString(string:"")

override func viewDidLoad() {
  super.viewDidLoad()

  let buttonTitleStr = NSMutableAttributedString(string:"My Button", attributes:attrs)
  attributedString.appendAttributedString(buttonTitleStr)
  yourButton.setAttributedTitle(attributedString, forState: .Normal)
}

106

Swift 5 / Xcode 11

  @IBOutlet weak var myButton: UIButton!

  let yourAttributes: [NSAttributedString.Key: Any] = [
      .font: UIFont.systemFont(ofSize: 14),
      .foregroundColor: UIColor.blue,
      .underlineStyle: NSUnderlineStyle.single.rawValue]
         //.double.rawValue, .thick.rawValue

  override func viewDidLoad() {
     super.viewDidLoad()

     let attributeString = NSMutableAttributedString(string: "Your button text",
                                                     attributes: yourAttributes)
     myButton.setAttributedTitle(attributeString, for: .normal)
  }

Swift 4 / Xcode 9

  @IBOutlet weak var myButton: UIButton!

  let yourAttributes : [NSAttributedStringKey: Any] = [
      NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14),
      NSAttributedStringKey.foregroundColor : UIColor.blue,
      NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue]
         //.styleDouble.rawValue, .styleThick.rawValue, .styleNone.rawValue

  override func viewDidLoad() {
    super.viewDidLoad()

    let attributeString = NSMutableAttributedString(string: "Your button text",
                                                    attributes: yourAttributes)
    myButton.setAttributedTitle(attributeString, for: .normal)
  }

Swift 3 / Xcode 8

  @IBOutlet weak var myButton: UIButton!

  let yourAttributes : [String: Any] = [
      NSFontAttributeName : UIFont.systemFont(ofSize: 14),
      NSForegroundColorAttributeName : UIColor.white,
      NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue] 
         //.styleDouble.rawValue, .styleThick.rawValue, .styleNone.rawValue

   override func viewDidLoad() {
      super.viewDidLoad()

      let attributeString = NSMutableAttributedString(string: "Your button text", 
                                                       attributes: yourAttributes)        
      myButton.setAttributedTitle(attributeString, for: .normal) 
    }

在此处输入图片说明


我在Swift 4中遇到此错误:无法将类型[[String:Any]'的值转换为预期的参数类型'[NSAttributedStringKey:Any]?”
巴甫洛斯州

let第二条设置为最后一行会导致Xcode 9.1 fyi崩溃
Zack Shapiro

29

如果您正在寻找一种无需继承的方法-

迅速3/4/5

// in swift 4 - switch NSUnderlineStyleAttributeName with NSAttributedStringKey.underlineStyle

extension UIButton {
    func underline() {
        guard let text = self.titleLabel?.text else { return }
        let attributedString = NSMutableAttributedString(string: text)
        //NSAttributedStringKey.foregroundColor : UIColor.blue
        attributedString.addAttribute(NSAttributedString.Key.underlineColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))
        attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: text.count))
        self.setAttributedTitle(attributedString, for: .normal)
    }
}



extension UILabel {
    func underline() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length - 1))
            attributedText = attributedString
        }
    }
}

19

StoryBoard:如果要对StoryBoard的文本加下划线。

  • 选择按钮或标签标题为“已归因”。
  • 选择要加下划线的文本范围。
  • 右键单击并选择字体,然后选择下划线。

在此处输入图片说明


18

根据先前的一些答案,我决定创建一个易于在您的应用中实现的类

斯威夫特4

import UIKit

class UnderlineTextButton: UIButton {

override func setTitle(_ title: String?, for state: UIControlState) {
    super.setTitle(title, for: .normal)
    self.setAttributedTitle(self.attributedString(), for: .normal)
}

private func attributedString() -> NSAttributedString? {
    let attributes : [NSAttributedStringKey : Any] = [
        NSAttributedStringKey.font : UIFont.systemFont(ofSize: 19.0),
        NSAttributedStringKey.foregroundColor : UIColor.red,
        NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
    ]
    let attributedString = NSAttributedString(string: self.currentTitle!, attributes: attributes)
    return attributedString
  }
}

从代码中我这样称呼它 button.setTitle(author, for: .normal)


15

感谢您发布代码,目前尚不清楚您根本不知道如何创建属性字符串。

这应该工作:

var attrs = [
    NSFontAttributeName : UIFont.systemFontOfSize(19.0),
    NSForegroundColorAttributeName : UIColor.redColor(),
    NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue
]

Swift 4版本:

var attrs : [NSAttributedStringKey : Any] = [
    NSAttributedStringKey.font : UIFont.systemFont(ofSize: 19.0),
    NSAttributedStringKey.foregroundColor : UIColor.red,
    NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]

当我添加NSUnderlineStyleAttributeName:NSUnderlineStyle.StyleSingle
moonvader

抱歉-我在ObjC和Swift之间混合了一些东西。您需要.rawValue
Glorfindel

我不知道为什么,但是按钮标签没有改变
moonvader 2015年

@moonvader处理按钮时,不能通过直接访问来更改标签titleLabel;相反,您必须使用button.setAttributedTitle(attributedString, forState: .Normal)
Nathaniel Blumer

11

@ShlomoKoppel回答Swift 4.2

extension UIButton {
    func underline() {
        guard let text = self.titleLabel?.text else { return }
        let attributedString = NSMutableAttributedString(string: text)
        //NSAttributedStringKey.foregroundColor : UIColor.blue
        attributedString.addAttribute(NSAttributedString.Key.underlineColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))
        attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: text.count))
        self.setAttributedTitle(attributedString, for: .normal)
    }
}



extension UILabel {
    func underlineMyText() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length - 1))
            attributedText = attributedString
        }
    }
}

6

这是在情节提要上完成的。(Xcode 9.1)

  1. 在视图中选择Button对象。
  2. 打开字体设置

在此处输入图片说明

  1. 选择单个下划线

在此处输入图片说明

  1. 输入文字,然后按[Enter]

1
如果计算机上未安装字体,则此选项不起作用。如果您已将自定义字体添加到项目中,但未在本地安装,则该字体不会显示在可用选项中。
B拉德

4

这是我的解决方案。老实说,您可能需要一个以上的位置,所以让我们创建一个扩展。这是很快的5.0干杯:)

extension UIButton {
    func underline() {
        guard let title = self.titleLabel else { return }
        guard let tittleText = title.text else { return }
        let attributedString = NSMutableAttributedString(string: (tittleText))
        attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: (tittleText.count)))
        self.setAttributedTitle(attributedString, for: .normal)
    }
}

您可以像这样使用它。

    override func viewDidLoad() {
     super.viewDidLoad()
     button.underline()
}

3
  • 斯威夫特5.2.4
  • Xcode 11.5
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.underlineStyle: 1,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13),
NSAttributedString.Key.foregroundColor: UIColor.systemGray3
]

let attributedString = NSMutableAttributedString(string: "Text here", attributes: attributes)
button.setAttributedTitle(NSAttributedString(attributedString: attributedString), for: .normal)

2

快速5

var attrs : [NSAttributedString.Key : Any] = [
    NSAttributedString.Key.font : UIFont.systemFont(ofSize: 19.0),
    NSAttributedString.Key.foregroundColor : UIColor.blue,
    NSAttributedString.Key.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]

2

@ shlomo-koppel答案按钮标题的修改版,如果您以编程方式设置/更改按钮标题,它将起作用(就像我使用本地化的情况一样)

extension UIButton {
    func underline() {
        guard let text = self.currentTitle else { return }
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(NSAttributedString.Key.underlineColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))
        attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: text.count))
        self.setAttributedTitle(attributedString, for: .normal)
    }
}

1

您也可以在此处添加下划线和粗体字。您可以在您的swift类文件中添加扩展

这是扩展区(已更新Swift 4)

extension NSMutableAttributedString {
 @discardableResult func bold(_ text:String) -> NSMutableAttributedString {

      let attrs : [NSAttributedStringKey : Any] = [
        NSAttributedStringKey.font : UIFont(name: "Montserrat-Bold", size: 12)!,
        NSAttributedStringKey.foregroundColor : UIColor.white,
        NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue]
    let boldString = NSMutableAttributedString(string: text, attributes: attrs)
    self.append(boldString)
    return self
 }

 @discardableResult func normal(_ text:String)->NSMutableAttributedString {
      let attrs : [NSAttributedStringKey : Any] = [
        NSAttributedStringKey.font : UIFont(name: "Montserrat-Regular", size: 12)!,
        NSAttributedStringKey.foregroundColor : UIColor.white
    ]
    let normal =  NSAttributedString(string: text,  attributes:attrs)
    self.append(normal)
    return self
 }

}

您可以像这样使用它:

let FormattedText = NSMutableAttributedString()
      FormattedText
           .normal("By signing in, you agree with our ")
           .bold("Terms of Service")

yourLabel.attributedText = FormattedText

结果将像这样显示 在此处输入图片说明


0

可能不是最好的方法,但我举了一个示例,将其与单独的类一起使用,并且仅进行了one line调用以获取文本。

这是我的课:

import Foundation
import UIKit

enum AttributedTextsType {
    case underlined
    case bold
    case boldUnderlined
}

class AttributedTexts {
    private static func underlinedText(color: UIColor, size: CGFloat) -> [NSAttributedString.Key : Any] {
    let attrs = [
        NSAttributedString.Key.font : UIFont.systemFont(ofSize: size),
        NSAttributedString.Key.foregroundColor : color,
        NSAttributedString.Key.underlineStyle : 1] as [NSAttributedString.Key : Any]
    return attrs
    }

    private static func getAttibute(type: AttributedTextsType, color: UIColor, size: CGFloat) -> [NSAttributedString.Key : Any] {
        var attributes: [NSAttributedString.Key : Any]!
        switch type {
        case .underlined:
            attributes = AttributedTexts.underlinedText(color: color, size: size)
            break
        case .bold:
            attributes = AttributedTexts.underlinedText(color: color, size: size)
            break
        case .boldUnderlined:
            attributes = AttributedTexts.underlinedText(color: color, size: size)
            break
        }
        return attributes
    }

    static func set(string: String, color: UIColor, type: AttributedTextsType, size: CGFloat = 19.0) -> NSMutableAttributedString {
        let attributes = getAttibute(type: type, color: color, size: size)
        let attributedString = NSMutableAttributedString(string:"")
        let buttonTitleStr = NSMutableAttributedString(string: string, attributes: attributes)
        attributedString.append(buttonTitleStr)
        return attributedString
    }
}

用法 let attributedString = AttributedTexts.set(string: "Skip", color: .white, type: .underlined, size: 19.0)

最好的祝福

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.