1

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

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

Use of unresolved identifier 'NSParagraphStyleAttributeName'

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

4

4 回答 4

4

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

}
于 2020-07-10T15:29:33.207 回答
3

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

于 2018-04-21T09:32:19.137 回答
1

这对我有用。

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
            }
        }
    }
于 2019-11-20T18:21:25.147 回答
-2

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

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

于 2019-01-07T21:01:01.940 回答