如何在 UILabel 中快速划线?

如何在雨燕 UILabel下划线?我搜索了 Objective-C 文件,但是无法让它们在 Swift 中工作。

158500 次浏览

您可以使用 NSAttributedString来完成这项工作

例如:

let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString

剪辑

为了对一个 UILabel 的所有文本具有相同的属性,我建议您对 UILabel 和覆盖文本进行子类化,如下所示:

Swift 5

与 Swift 4.2相同,但是: 相对于旧的 NSMakeRange,您应该更喜欢 Swift 初始化器 NSRange,您可以缩短为 .underlineStyle,并且换行符可以提高长方法调用的可读性。

class UnderlinedLabel: UILabel {


override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSRange(location: 0, length: text.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}

Swift 4.2

class UnderlinedLabel: UILabel {


override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSMakeRange(0, text.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}

Swift 3.0

class UnderlinedLabel: UILabel {
    

override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSMakeRange(0, text.characters.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}

然后你把你的短信写成这样:

@IBOutlet weak var label: UnderlinedLabel!
    

override func viewDidLoad() {
super.viewDidLoad()
        

label.text = "StringWithUnderLine"
}

老:

Swift (2.0至2.3) :

class UnderlinedLabel: UILabel {
    

override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSMakeRange(0, text.characters.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
            

self.attributedText = attributedText
}
}
}

迅捷1.2:

class UnderlinedLabel: UILabel {
    

override var text: String! {
didSet {
let textRange = NSMakeRange(0, count(text))
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
            

self.attributedText = attributedText
}
}
}

你可以使用 Interface Builder 在 UILabel文本下划线。

这是我的答案的链接: 在故事板中为部分文本 UILabel 添加下划线属性

Swift 5 & 4.2一行:

label.attributedText = NSAttributedString(string: "Text", attributes:
[.underlineStyle: NSUnderlineStyle.single.rawValue])

Swift 4一行:

label.attributedText = NSAttributedString(string: "Text", attributes:
[.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])

斯威夫特3一行:

label.attributedText = NSAttributedString(string: "Text", attributes:
[NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])

如果你正在寻找一种不继承遗产的方法:

Swift 5

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))
attributedText = attributedString
}
}
}

斯威夫特3/4

// in swift 4 - switch NSUnderlineStyleAttributeName with NSAttributedStringKey.underlineStyle
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))
attributedText = attributedString
}
}
}




extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
self.setAttributedTitle(attributedString, for: .normal)
}
}

迅速变化。 记住使用 StyleSingle.rawValue而不是 单身

   'let attributedString = NSAttributedString(string: "Testing")
let textRange = NSMakeRange(0, attributedString.length)
let underlinedMessage = NSMutableAttributedString(attributedString: attributedString)
underlinedMessage.addAttribute(NSAttributedStringKey.underlineStyle,
value:NSUnderlineStyle.styleSingle.rawValue,
range: textRange)
label.attributedText = underlinedMessage

`

上面的答案在我的构建环境中导致了一个错误。

这在 Swift 4.0中不起作用:

attributedText.addAttribute(NSUnderlineStyleAttributeName,
value: NSUnderlineStyle.styleSingle.rawValue,
range: textRange)

试试这个:

attributedText.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: textRange)

希望这能帮到别人。

只是一个小修复的 Shlome 答案在 Swift 4Xcode 9

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


extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: NSRange(location: 0, length: (self.titleLabel?.text!.count)!))
self.setAttributedTitle(attributedString, for: .normal)
}
}

为了 Swift 2.3

extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
self.setAttributedTitle(attributedString, forState: .Normal)
}
}

以及 ViewController

@IBOutlet var yourButton: UIButton!

ViewDidLoad方法中或者在函数中写

yourButton.underline()

它会在你的按钮的标题下面划线

//Swift 4 Version

 let attributedString  = NSMutableAttributedString(string: "Your Text Here", attributes: [NSAttributedStringKey.underlineStyle : true])


self.yourlabel.attributedText = attributedString

迅捷5:

1-创造获取属性化文本的 String 扩展名

extension String {


var underLined: NSAttributedString {
NSMutableAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
}


}

2-使用

按钮:

<#YourButton#>.setAttributedTitle(<#YourButtonTitle#>.underLined, for: .normal)

标签:

<#YourLabel#>.attributedText = <#YourLabelTitle#>.underLined

或者 < a href = “ https://stackoverflow. com/questions/28268060/add-underline-tribute-to-part-text-uilabel-in-storboard/30750184 # 30750184”> Stoyboard version

同样的答案在 Swift 4.2

对于 可用

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: textString.count))
self.attributedText = attributedString
}
}
}

如下呼叫 UILabel

myLable.underline()

对于 UIButton

extension UIButton {
func underline() {
if let textString = self.titleLabel?.text {


let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: textString.count))
self.setAttributedTitle(attributedString, for: .normal)
}


}
}

如下呼叫 UIButton

myButton.underline()

我研究了以上的答案,其中一些是强制展开 短信值。我将建议通过安全地拆开包装来获得价值。这将避免在出现空值的情况下崩溃。 希望这能有所帮助:)

下划线到一个句子中的多个字符串。

extension UILabel {
func underlineMyText(range1:String, range2:String) {
if let textString = self.text {


let str = NSString(string: textString)
let firstRange = str.range(of: range1)
let secRange = str.range(of: range2)
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: firstRange)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: secRange)
attributedText = attributedString
}
}
}

这样使用。

    lbl.text = "By continuing you agree to our Terms of Service and Privacy Policy."
lbl.underlineMyText(range1: "Terms of Service", range2: "Privacy Policy.")

如果您希望只实现标签的一半部分,如下划线:-//For Swift 4.0 + ,也可以使用此方法

let attributesForUnderLine: [NSAttributedString.Key: Any] = [
.font: UIFont(name: AppFont.sourceSansPro_Regular, size: 12) ?? UIFont.systemFont(ofSize: 11),
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue]


let attributesForNormalText: [NSAttributedString.Key: Any] = [
.font: UIFont(name: AppFont.sourceSansPro_Regular, size: 12) ?? UIFont.systemFont(ofSize: 11),
.foregroundColor: AppColors.ColorText_787878]


let textToSet = "Want to change your preferences? Edit Now"
let rangeOfUnderLine = (textToSet as NSString).range(of: "Edit Now")
let rangeOfNormalText = (textToSet as NSString).range(of: "Want to change your preferences?")


let attributedText = NSMutableAttributedString(string: textToSet)
attributedText.addAttributes(attributesForUnderLine, range: rangeOfUnderLine)
attributedText.addAttributes(attributesForNormalText, range: rangeOfNormalText)
yourLabel.attributedText = attributedText

斯威夫特4、4.2和5

  @IBOutlet weak var lblUnderLine: UILabel!

我需要在 UILabel 中的特定文本下划线。

    let strSignup = "Don't have account? SIGNUP NOW."
let rangeSignUp = NSString(string: strSignup).range(of: "SIGNUP NOW.", options: String.CompareOptions.caseInsensitive)
let rangeFull = NSString(string: strSignup).range(of: strSignup, options: String.CompareOptions.caseInsensitive)
let attrStr = NSMutableAttributedString.init(string:strSignup)
attrStr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.font : UIFont.init(name: "Helvetica", size: 17)! as Any],range: rangeFull)
attrStr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.font : UIFont.init(name: "Helvetica", size: 20)!,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue as Any],range: rangeSignUp) // for swift 4 -> Change thick to styleThick
lblUnderLine.attributedText = attrStr

输出

enter image description here

一个用于设置和删除 Swift 5用户界面按钮下划线的类。我希望这有所帮助

import Foundation
import UIKit


class UiUtil {


static let underlineThickness = 2
    

class func removeUnderlineFromButton( _ button:UIButton ) {
if let str = button.titleLabel?.attributedText {
let attributedString = NSMutableAttributedString( attributedString: str )
attributedString.removeAttribute(.underlineStyle, range:
NSRange.init(location: 0, length: attributedString.length))
button.setAttributedTitle(attributedString, for: .normal)
}
}


class func setUnderlineFromButton( _ button:UIButton ) {
if let str = button.titleLabel?.attributedText {
let attributedStringUnderline = NSMutableAttributedString( attributedString:
str  )
attributedStringUnderline.addAttribute(
NSAttributedString.Key.underlineStyle,
value: underlineThickness,
range: NSRange.init(location: 0, length: attributedStringUnderline.length)
)
button.setAttributedTitle(attributedStringUnderline, for: .normal)
}
}


}

我的应用程序里有一个算法。在这个算法中,即使在单词之间有空格,也可以给子字符串加下划线

extension NSMutableAttributedString{


static func  findSubStringAndUnderlineIt(subStringToBeFound : String,totalString : String)->  NSMutableAttributedString?{
        

let attributedString = NSMutableAttributedString(string: totalString)


var spaceCount = 0
        

if subStringToBeFound.contains(" "){
spaceCount = subStringToBeFound.components(separatedBy:" ").count-1
}


        

if  let range = attributedString.string.range(of: subStringToBeFound, options: .caseInsensitive){
        

attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange((range.lowerBound.utf16Offset(in: subStringToBeFound)) ,(range.upperBound.utf16Offset(in: subStringToBeFound)) +
spaceCount))
return attributedString
}
return attributedString
        

}
    

}

在使用部分

 lblWarning.attributedText = NSMutableAttributedString.findSubStringAndUnderlineIt(subStringToBeFound:"Not: Sadece uygulamanın reklamları kaldırılacaktır.", totalString: lblWarning.text!)