ios Swift 中的下划线按钮文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31357238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:49:46  来源:igfitidea点击:

Underline button text in Swift

iosxcodeswift

提问by moonvader

I have UIButton. In interface builder I set its title to be 'Attributed'. How can I make its title to be underlined from code in Swift?

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

@IBOutlet weak var myBtn: UIButton!

I created a function called on the touchUpInside event of this button:

我创建了一个在这个按钮的 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;

But still no result. Also I need to know how to access the underline attribute. Text, size and color stay the same.

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

回答by A.Kant

Swift 5 / Xcode 11

斯威夫特 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

斯威夫特 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

斯威夫特 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) 
    }

enter image description here

在此处输入图片说明

回答by 36 By Design

Here you go, just tested it. (works in xCode 7 Beta at least)

给你,刚刚测试了一下。(至少适用于 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)
}

回答by Shlomo Koppel

if you are looking for a way to do this without inheritance -

如果您正在寻找一种无需继承即可执行此操作的方法-

swift 3/4/5

快速 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
        }
    }
}

回答by Max Tymchii

Based on some of previous answers I decide to make a class that can be easy implemented into your apps

根据之前的一些答案,我决定创建一个可以轻松实现到您的应用程序中的类

Swift 4

斯威夫特 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
  }
}

From code I call it on such a way button.setTitle(author, for: .normal)

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

回答by Glorfindel

Thanks for posting your code, it wasn't clear that you knew how to create an attributed string at all.

感谢您发布您的代码,您根本不清楚如何创建属性字符串。

This should work:

这应该有效:

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

Swift 4 version:

斯威夫特 4 版本:

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

回答by Sukhwinder Singh

StoryBoard:If you want to Underline text from storyBoard.

故事板:如果你想从故事板中给文本加下划线。

  • Select button or label title as Attributed.
  • Select range of text which you want to underline.
  • Right click and choose Font then select underline.
  • 选择按钮或标签标题作为属性。
  • 选择要加下划线的文本范围。
  • 右键单击并选择字体,然后选择下划线。

enter image description here

在此处输入图片说明

回答by Kiran Jasvanee

@ShlomoKoppelanswer in Swift 4.2

@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
        }
    }
}

回答by tBug

This is my solution. And to be honest you probably need this more than one place, so let's create an extension. This is swift 5.0 Cheers :)

这是我的解决方案。老实说,您可能需要不止一个地方,所以让我们创建一个扩展。这是 swift 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)
    }
}

And you can use it like this.

你可以像这样使用它。

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

回答by Chong Hann

Here is done on the storyboard. (Xcode 9.1)

这是在故事板上完成的。(Xcode 9.1)

  1. Select the Button object in your view.
  2. Open Fonts Settings
  1. 在您的视图中选择 Button 对象。
  2. 打开字体设置

enter image description here

在此处输入图片说明

  1. Select Single Underline
  1. 选择单下划线

enter image description here

在此处输入图片说明

  1. Type your text, press [Enter]
  1. 输入您的文本,按 [Enter]

回答by Talha Rasool

For swift 5

快速 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
]