簡體   English   中英

如何快速在 UILabel 下划線?

[英]How to underline a UILabel in swift?

如何在 Swift 中給UILabel加下划線? 我搜索了 Objective-C 的那些,但不能完全讓它們在 Swift 中工作。

您可以使用NSAttributedString執行此操作

例子:

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

編輯

要使一個 UILabel 的所有文本具有相同的屬性,我建議您將 UILabel 子類化並覆蓋文本,如下所示:

斯威夫特 5

與 Swift 4.2 相同,但是:與舊的NSMakeRange ,您應該更喜歡 Swift 初始化NSRange NSMakeRange ,您可以縮短為.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
        }
    }
}

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

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

老的:

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

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

Swift 3 一個班輪:

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

如果您正在尋找一種無需繼承即可執行此操作的方法:

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

斯威夫特 5:

1-創建一個字符串擴展來獲取attributedText

extension String {

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

}

2-使用

在按鈕上:

button.setAttributedTitle(yourButtonTitle.underLined, for: .normal)

關於標簽:

label.attributedText = yourLabelTitle.underLined

玩具板版本

只是對Swift 4Xcode 9 中的 Shlome 答案進行了一點修復。

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

您可以使用 Interface Builder 在UILabel文本下划線。

這是我的答案的鏈接: 向情節提要中的部分文本 UILabel 添加下划線屬性

Swift 4.2 中的相同答案

對於UILable

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

我查看了上面的答案,其中一些是強制展開文本值。 我會建議通過安全拆包來獲得價值。 這將避免在 nil 值的情況下崩潰。 希望這可以幫助 :)

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

輸出

在此處輸入圖片說明

給句子中的多個字符串加下划線。

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.")

斯威夫特 4 的變化。 記住使用NSUnderlineStyle.styleSingle.rawValue而不是NSUnderlineStyle.styleSingle

   '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+

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

上面的答案導致我的構建環境出錯。

這在 Swift 4.0 中不起作用:

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

試試這個:

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

希望這有助於某人。

// Swift 4 版本

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

self.yourlabel.attributedText = attributedString

對於 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 5 的 UIbuttons 設置和刪除下划線的類。我希望這會有所幫助

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM