【问题标题】:How to Increase Line spacing in UILabel in Swift 4如何在 Swift 4 中增加 UILabel 中的行距
【发布时间】:2018-04-21 08:55:14
【问题描述】:

我想增加 UILabel 中的行间距,但我不知道怎么做。

我在 Stackoverflow 上找到了这个解决方案 [https://stackoverflow.com/a/39158698/8633963],但我的 Xcode 总是显示这个:

Use of unresolved identifier 'NSParagraphStyleAttributeName'

我认为答案是正确的,但它对我不起作用。 谁能帮忙解决这个问题?

【问题讨论】:

  • 答案在提到的 SO 链接中。你看别人的回答了吗? stackoverflow.com/a/39158698/8633963 意见。与其以编程方式定义,不如从 Interface builder 中执行相同的操作。

标签: swift xcode uilabel nsparagraphstyle line-spacing


【解决方案1】:

斯威夫特 5

import UIKit

extension UILabel {
    
    func setLineHeight(lineHeight: CGFloat) {
        guard let text = self.text else { return }
        
        let attributeString = NSMutableAttributedString(string: text)
        let style = NSMutableParagraphStyle()
        
        style.lineSpacing = lineHeight
        attributeString.addAttribute(
            NSAttributedString.Key.paragraphStyle,
            value: style,
            range: NSMakeRange(0, attributeString.length))
        
        self.attributedText = attributeString
    }

}

【讨论】:

    【解决方案2】:

    在这种情况下,在 Swift 4 中,您必须使用 NSAttributedStringKey.paragraphStyle 而不是 NSParagraphStyleAttributeName

    【讨论】:

      【解决方案3】:

      这对我有用。

      import UIKit
      
          extension UILabel {
      
              func setLineHeight(lineHeight: CGFloat) {
                  let text = self.text
                  if let text = text {
                      let attributeString = NSMutableAttributedString(string: text)
                      let style = NSMutableParagraphStyle()
      
                      style.lineSpacing = lineHeight
                      attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, count(text)))
                      self.attributedText = attributeString
                  }
              }
          }
      

      【讨论】:

        【解决方案4】:

        看看这个可行的非常简单的解决方案!

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CommentTVCCell
        
            // Configure the cell...
        
        
            cell.myLabel?.text = "\n[\(indexPath.row + 1)]\n\n" + itemArray[indexPath.row].name
        
            //
        
            return cell 
        }
        

        //注意使用 \n 来加载返回或任意数量。确保它们在字符串指定范围内。

        【讨论】:

        • 我要冒昧地说 OP 不想要使用 TableView 的解决方案
        猜你喜欢
        • 2017-01-02
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 2016-05-03
        • 1970-01-01
        • 2021-08-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多