Swift中的下划线按钮文本

时间:2015-07-11 12:34:54

标签: ios xcode swift

我有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;

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

14 个答案:

答案 0 :(得分:69)

在这里,你去试试吧。 (至少在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)
}

答案 1 :(得分:65)

Swift 5 / Xcode 10

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

enter image description here

答案 2 :(得分:20)

如果您正在寻找一种没有继承的方法 -

swift 3/4

// 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)
        attributedString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.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(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: attributedString.length - 1))
          attributedText = attributedString
        }
    }
}

答案 3 :(得分:14)

感谢发布您的代码,您还不知道如何创建归因字符串。

这应该有效:

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
]

答案 4 :(得分:13)

根据之前的一些答案,我决定制作一个可以轻松实现到您的应用中的课程

Swift 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)

答案 5 :(得分:6)

Swift 4.2

@ShlomoKoppel

extension UIButton {
    func underlineMyText() {
        guard let text = self.titleLabel?.text else { return }

        let attributedString = NSMutableAttributedString(string: text)
        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 :(得分:3)

StoryBoard::如果要在StoryBoard上加下划线。

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

enter image description here

答案 7 :(得分: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)

答案 8 :(得分: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
]

答案 9 :(得分: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)
    }
}

答案 10 :(得分:1)

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

这是扩展(Swift 4已更新)

public class MyClass
{
    public List<string> Columns { get; set; }
    public List<MyRow> Rows { get; set; }
}

public class MyRow : DynamicObject
{
    public MyClass OwnerClass { get; set; }
    public List<object> Values { get; set; }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return OwnerClass.Columns;
    }

    public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
    {
        if (indexes.Length == 1 && OwnerClass != null)
        {
            if (indexes[0] is string stringIndex && OwnerClass.Columns.Contains(stringIndex))
            {
                result = Values[OwnerClass.Columns.IndexOf(stringIndex)];
                return true;
            }
            else if (indexes[0] is int intIndex)
            {
                result = Values[intIndex];
                return true;
            }
        }
        result = null;
        return false;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if ((!string.IsNullOrEmpty(binder.Name) && OwnerClass.Columns.Contains(binder.Name)))
        {
            result = Values[OwnerClass.Columns.IndexOf(binder.Name)];
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
    {
        if (indexes.Length == 1 && OwnerClass != null)
        {
            if (indexes[0] is string stringIndex && OwnerClass.Columns.Contains(stringIndex))
            {
                Values[OwnerClass.Columns.IndexOf(stringIndex)] = value;
                return true;
            }
            else if (indexes[0] is int intIndex)
            {
                Values[intIndex] = value;
                return true;
            }
        }
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if ((!string.IsNullOrEmpty(binder.Name) && OwnerClass.Columns.Contains(binder.Name)))
        {
            Values[OwnerClass.Columns.IndexOf(binder.Name)] = value;
            return true;
        }
        return false;
    }
}

}

您可以像这样使用它:

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
 }

,结果将显示为 enter image description here

答案 11 :(得分:0)

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

  1. 在视图中选择Button对象。
  2. Open Fonts Settings
  3. Select Single Underline
  4. 输入文字,然后按[Enter]

答案 12 :(得分:0)

这是我的解决方案。老实说,您可能需要一个以上的位置,所以让我们创建一个扩展。 这是快速的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()
}

答案 13 :(得分: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)

最诚挚的问候