Underline button text in Swift

2020-05-14 13:48发布

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?

@IBOutlet weak var myBtn: UIButton!

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

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.

标签: ios xcode swift
12条回答
戒情不戒烟
2楼-- · 2020-05-14 13:56

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

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()
}
查看更多
够拽才男人
3楼-- · 2020-05-14 13:56

For swift 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
]
查看更多
该账号已被封号
4楼-- · 2020-05-14 14:01

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

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

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

查看更多
何必那么认真
5楼-- · 2020-05-14 14:02

Here you can add an underline and bold face too. You can just add an extention in your swift class file

Here is the extention (Swift 4 updated)

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
 }

}

You can use it like this:

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

yourLabel.attributedText = FormattedText

and the Result will be display like this enter image description here

查看更多
我想做一个坏孩纸
6楼-- · 2020-05-14 14:05

Here is done on the storyboard. (Xcode 9.1)

  1. Select the Button object in your view.
  2. Open Fonts Settings

enter image description here

  1. Select Single Underline

enter image description here

  1. Type your text, press [Enter]
查看更多
Summer. ? 凉城
7楼-- · 2020-05-14 14:06

May not be the best approach but I made an example to use it with a separated class and make only a one line call to get the text.

Here is my class:

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

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

Best regards

查看更多
登录 后发表回答