繁体   English   中英

如何在 Swift 4 中增加 UILabel 中的行距

[英]How to Increase Line spacing in UILabel in Swift 4

我想增加 UILabel 中的行间距,但我不知道如何。

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

Use of unresolved identifier 'NSParagraphStyleAttributeName'

我认为答案是正确的,但它对我不起作用。 任何人都可以帮助解决这个问题吗?

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

斯威夫特 5

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(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, attributeString.length))
            self.attributedText = attributeString
        }
    }

}

这对我有用。

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

看看这个非常简单的有效解决方案!

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 加载返回或任意数量的返回。 确保它们在字符串指定内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM