Подчеркнуть текст кнопки в 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;
Но до сих пор нет результата. Также мне нужно знать, как получить доступ к атрибуту подчеркивания. Текст, размер и цвет остаются неизменными.
Ответы
Ответ 1
Здесь вы идете, просто протестировали его. (работает в 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)
}
Ответ 2
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]()
Ответ 3
если вы ищете способ сделать это без наследования -
быстрый 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)
//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(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: attributedString.length - 1))
attributedText = attributedString
}
}
}
Ответ 4
Спасибо за размещение вашего кода, не было ясно, что вы вообще знали, как создать атрибутивную строку.
Это должно работать:
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
]
Ответ 5
Основываясь на некоторых предыдущих ответах, я решил создать класс, который можно легко внедрить в ваши приложения.
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)
Ответ 6
@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
}
}
}
Ответ 7
Здесь сделано на раскадровке. (Xcode 9.1)
- Выберите объект Button в вашем представлении.
- Настройки открытого шрифта
![enter image description here]()
- Выберите одиночное подчеркивание
![enter image description here]()
- Введите текст, нажмите [Enter]
Ответ 8
Здесь вы можете добавить подчеркивание и жирный шрифт тоже. Вы можете просто добавить расширение в свой файл класса 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
и результат будет отображаться так ![enter image description here]()
Ответ 9
Это моё решение. И, честно говоря, вам, вероятно, нужно больше, чем одно место, поэтому давайте создадим расширение. Это быстрое ура 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()
}
Ответ 10
StoryBoard: Если вы хотите подчеркнуть текст из storyBoard.
- Выберите заголовок кнопки или метки в качестве атрибута.
- Выберите диапазон текста, который вы хотите подчеркнуть.
- Щелкните правой кнопкой мыши и выберите "Шрифт", затем выберите подчеркивание.
![enter image description here]()