【问题标题】:How to underline a UILabel in swift?如何快速下划线 UILabel?
【发布时间】:2015-03-19 03:40:11
【问题描述】:

如何在 Swift 中为UILabel 加下划线?我搜索了 Objective-C 的,但无法让它们在 Swift 中工作。

【问题讨论】:

标签: ios swift overriding uilabel nsattributedstring


【解决方案1】:

您可以使用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 相同,但:您应该更喜欢 Swift 初始化程序 NSRange 而不是旧的 NSMakeRange,您可以缩短为 .underlineStyle 并且换行符提高了长方法调用的可读性。 p>

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

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

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

【讨论】:

  • 去下划线最好的方法是什么?
  • 我一直在想:为什么我们必须使用 rawValue 否则它会崩溃?
  • 在创建 textRange NSRange 时,您应该传递 UTF16 计数而不是字符计数
  • 我已经改变了这个解决方案,在初始化时添加了一个下划线,这样我们就可以很容易地在故事板中使用它required init?(coder: NSCoder) { super.init(coder: coder) self.addUnderline() // your code }
  • 更好的解决方案算法更好的解决方案你可以看我的答案stackoverflow.com/questions/28053334/…
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    斯威夫特 5:

    1- 创建一个字符串扩展来获取属性文本

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

    2- 使用

    打开按钮:

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

    在标签上:

    label.attributedText = yourLabelTitle.underLined
    

    或者Stoyboard version

    【讨论】:

      【解决方案4】:

      如果您正在寻找一种无需继承的方法:

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

      【讨论】:

      • 在创建NSRange 时,您应该传递UTF16 计数而不是字符计数
      【解决方案5】:

      一个用于为 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)
                 }
            }
      
         }
      

      【讨论】:

        【解决方案6】:

        Swift 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
        

        输出

        【讨论】:

          【解决方案7】:

          如果你只想将标签的一半作为下划线,你也可以使用它:- //对于 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
          

          【讨论】:

            【解决方案8】:

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

            【讨论】:

            • NSUnderlineStyle.styleSingle.rawValue 在 swift 4.2 中已重命名为 NSUnderlineStyle.single.rawValue
            • 如何取消下划线?
            • @N.Der 再次设置一个普通文本来标记
            【解决方案9】:

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

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

            【讨论】:

            • 你将如何跟踪触摸?
            【解决方案10】:

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

            我查看了上述答案,其中一些是强制展开 text 值。我会建议通过安全展开来获得价值。这将避免在 nil 值的情况下崩溃。 希望这会有所帮助:)

            【讨论】:

            • 简单美观
            • 在创建NSRange 时,您应该传递UTF16 计数而不是字符计数
            • 如果你已经有 UILabel 的扩展,IMO 调用 myButton.titleLabel?.underline() 会更简单,或者至少在 UIButton 扩展的 underline() 函数中使用它。
            【解决方案11】:

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

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

            【讨论】:

              【解决方案12】:

              // Swift 4 版本

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

              【讨论】:

                【解决方案13】:

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

                【讨论】:

                • 在创建NSRange 时,您应该传递UTF16 计数而不是字符计数
                【解决方案14】:

                上面的答案导致我的构建环境出错。

                这在 Swift 4.0 中不起作用:

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

                试试这个:

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

                希望这对某人有所帮助。

                【讨论】:

                  【解决方案15】:

                  Swift 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
                  

                  `

                  【讨论】:

                    【解决方案16】:

                    您可以使用 Interface Builder 为 UILabel 文本添加下划线。

                    这是我的答案的链接:Adding underline attribute to partial text UILabel in storyboard

                    【讨论】:

                    • 如果将文本重新绑定到标签,此方法将失败。
                    • @EricH 你是什么意思?
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-11-25
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2016-01-02
                    相关资源
                    最近更新 更多