【问题标题】:How do I change the letter spacing in a UILabel?如何更改 UILabel 中的字母间距?
【发布时间】:2016-10-07 23:18:31
【问题描述】:

我想更改 UIKit UILabel 中数字之间的间距,使其相等。

使用标准间距,标签如下所示:

我希望它看起来像这样:

如何做到这一点?

【问题讨论】:

    标签: ios uilabel spacing


    【解决方案1】:

    您可以在属性字符串上使用NSKernAttributeName 属性

    UILabel *label = [UILabel new];
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] 
                                       initWithString:@"127"];
    
    // The value paramenter defines your spacing amount, and range is 
    // the range of characters in your string the spacing will apply to. 
    // Here we want it to apply to the whole string so we take it from 0 to text.length.
    [text addAttribute:NSKernAttributeName 
                 value:@-0.5 
                 range:NSMakeRange(0, text.length)];
    
    [label setAttributedText:text];
    

    【讨论】:

    • 感谢 J2K。我忘记了将字距应用于字符串子范围的能力。
    【解决方案2】:

    最简单的方法是创建一个自定义 UILabel 类并从 Storyboard 中设置字母间距。

    open class CustomLabel : UILabel {
        @IBInspectable open var characterSpacing:CGFloat = 1 {
            didSet {
                let attributedString = NSMutableAttributedString(string: self.text!)
                attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
                self.attributedText = attributedString
            }
    
        }
    }
    

    【讨论】:

    • 永远不会应用默认值。你应该修复代码。
    • 如果您使用界面生成器,这只是“最简单”的方式。
    【解决方案3】:

    关于快速实现的样子

    let text = "TIPS, ARTICLES & BEST OFFERS"
    label.attributedText = NSAttributedString(string: text, attributes: [.kern: 3.12])
    

    【讨论】:

      【解决方案4】:

      您可以使用 NSAttributedString 并使用 NSKernAttributeName 属性。默认值为 0,因此您需要将其设置为负数。

      https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/#//apple_ref/doc/constant_group/Character_Attributes

      在 Obj-C 中你可以这样做:

      NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString: @"Test test test test "];
      [attrStr addAttribute:NSKernAttributeName value:@(4.0) range:NSMakeRange(0, attrStr.length)];
      
      label.attributedText = attrStr;
      

      在 Swift 中你可以这样做:

      let myTitle = "my title"
      let titleLabel = UILabel()
      let attributes: NSDictionary = [
          NSFontAttributeName:UIFont(name: "FONT_NAME", size: TEXT_SIZE),
          NSKernAttributeName:CGFloat(2.0)
      ]
      
      let attributedTitle = NSAttributedString(string: myTitle, attributes:attributes as? [String : AnyObject])
      
      titleLabel.attributedText = attributedTitle
      

      【讨论】:

        【解决方案5】:

        可以使用NSKernAttributeName

        但要更正其他答案:不适用于全文长度,而是 (text.length - 1)

        在字母中添加负间距或正间距,最后一个不需要。假设您要添加一个正间距,它会在最后一个字母之后的间距中结束。居中的字符串将不再居中。这同样适用于负间距。

        NSString *text = @"Sample Text";    
        UILabel *label = [UILabel new]
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: text];
        [attributedString addAttribute:NSKernAttributeName value:[NSNumber numberWithDouble:-1.0] range:NSMakeRange(0, text.length-1)];
        
        [label setAttributedTitle:attributedString forState:UIControlStateNormal];
        

        应用于全文长度。

        应用于(文本长度 - 1)。

        【讨论】:

        • 非常有用的补充!只有一件事:我们在传入范围为 (0, -1) 的空字符串时遇到了问题。所以我添加了 max(0, text.length - 1) 以使其安全。
        【解决方案6】:

        我从@J2K 那里得到了答案,并将其翻译成 Swift 4.2 扩展。

        /// Set the text of the label but altering the kerning so that you can control the space between each characters.
        ///
        /// - Parameters:
        ///   - text: New content of the label
        ///   - kerning: Set a value between 0 and 1 to lower the space between characters. Above 0, spacing will be increased. 0 disables kerning.
        extension UILabel {
        
            func set(text: String, withKerning kerning: CGFloat) {
                let attributedString = NSMutableAttributedString(string: text)
        
                // The value parameter defines your spacing amount, and range is
                // the range of characters in your string the spacing will apply to.
                // Here we want it to apply to the whole string so we take it from 0 to text.count.
                attributedString.addAttribute(NSAttributedString.Key.kern, value: kerning, range: NSMakeRange(0, text.count))
        
                attributedText = attributedString
            }
        
        }
        

        【讨论】:

          【解决方案7】:

          如果您想在不修改任何内容(针对特定字体)的情况下将字母间距属性应用于 Interface Builder 中的所有 UILabel:

          斯威夫特 4:

          /**
           * Applies letter spacing to selected fonts in UILabels from IB.
           *
           * - author Alexander Volkov
           * - version 1.0
           */
          extension UILabel {
          
              /// Applies letter spacing
              open override func awakeFromNib() {
                  super.awakeFromNib()
                  applyLetterSpacing()
              }
          
              /// Applies letter spacing
              ///
              /// - Parameter aDecoder: the decoder
              /// - Returns: UILabel instance
              open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
                  let label = super.awakeAfter(using: aDecoder)
                  self.applyLetterSpacing()
                  return label
              }
          
          
              /// Applies letter spacing
              func applyLetterSpacing() {
                  if font.fontName.contains("Oswald", caseSensitive: false) {
                      let characterSpacing: CGFloat = 1
                      let string = NSMutableAttributedString(string: self.text!)
                      string.addAttribute(.kern, value: characterSpacing, range: NSRange(location: 0, length: string.length - 1))
                      self.attributedText = string
                  }
              }
          }
          

          【讨论】:

            【解决方案8】:
            NSString *myString = @"127";
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:myString];
            
            float letterSpacing = -1.50f; // change spacing here
            [attributedString addAttribute:NSKernAttributeName value:@(letterSpacing) range:NSMakeRange(0, [myString length])];
            [myLabel setAttributedText:attributedString];
            

            有关更多信息和结果,另请参阅:http://www.devsign.co/notes/tracking-and-character-spacing

            【讨论】:

              【解决方案9】:

              我发现这是最好的解决方案。它还包括 UIButton,应用可能已在界面生成器中设置的属性并适应不同的字体:

              extension UILabel {
              
                  open override func awakeFromNib() {
                      super.awakeFromNib()
                      applyLetterSpacing()
                  }
              
                  func applyLetterSpacing() {
                      // return if empty text
                      if((text ?? "").isEmpty) {
                          return
                      }
              
                      // default spacing
                      var spacing = 1
                      if(font.familyName == "Source Serif Pro") {
                          // custom spacing for different font
                          spacing = 2
                      }
                      var attributes = attributedText?.attributes(at: 0, effectiveRange: nil) ?? [:]
                      attributes[.kern] = spacing
                      attributedText = NSAttributedString(string: text ?? "", attributes: attributes)
                  }
              
              }
              

              对于按钮

              extension UIButton {
              
                  open override func awakeFromNib() {
                      super.awakeFromNib()
                      applyLetterSpacing()
                  }
              
                  func applyLetterSpacing() {
                      if((title(for: .normal) ?? "").isEmpty) {
                          return
                      }
                      var attributes = attributedTitle(for: .normal)?.attributes(at: 0,     effectiveRange: nil) ?? [:]
                      attributes[.kern] = 1
                      attributes[.foregroundColor] = titleColor(for: .normal)
                      setAttributedTitle(NSAttributedString(string: title(for: .normal) ?? "", attributes: attributes), for: .normal)
                  }
              }
              

              【讨论】:

                【解决方案10】:

                单击标签并转到您的属性检查器。将文本从纯文本更改为属性。您将有几个间距选项。希望这会有所帮助。

                【讨论】:

                • 你能解释一下吗,因为我看不到“字母间距”的选项
                猜你喜欢
                • 1970-01-01
                • 2011-07-05
                • 1970-01-01
                • 2014-12-06
                • 2011-12-11
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多