簡體   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