为什么multiline attributionString UITextView有不同的行高?

时间:2016-12-24 15:42:00

标签: ios uitextview

我在textView中使用相同的字体获得不同的行高

如何设置固定线高?

我做了很多尝试,感谢任何帮助,谢谢

  • 设置NSMutableParagraphStyle lineSpacing无用
  • 设置lineHeightMultiple是为了让差异更明显

[1]

演示

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 1000))
let data: [String] = [
    "商品名称: 巧克力",
    "商品名称: 巧克力",
    "商品名称: 巧克力",
    "注册未成功,请验证电子邮件",
    "注册未成功,请验证电子邮件",
    "注册未成功,请验证电子邮件",
    "测试文字, 测试文字,测试文字",
    "测试文字, 测试文字,测试文字",
    "测试文字, 测试文字,测试文字",
]
let textView = UITextView(frame: view.frame)


let paragraphStyle = NSMutableParagraphStyle()
let bodyFont = UIFont.systemFont(ofSize: 20.0)
paragraphStyle.lineHeightMultiple = 4
var stripe = false

// attributedString
let mutableAttributedString = NSMutableAttributedString(string: "Test TextViewAttributedString\n", attributes: [
    NSFontAttributeName: UIFont.systemFont(ofSize: 18.0)
    ])

for text: String in data {
    var backgroundColor = UIColor(red:0.13, green:0.38, blue:0.95, alpha:1.00)
    if stripe {
        backgroundColor = UIColor(red:0.92, green:0.12, blue:0.38, alpha:1.00)
    }

    let contentAttributedString = NSAttributedString(string: text, attributes: [
        NSBackgroundColorAttributeName: backgroundColor,
        NSParagraphStyleAttributeName: paragraphStyle,
        NSFontAttributeName: bodyFont
        ])
    mutableAttributedString.append(contentAttributedString)
    stripe = !stripe

    // add newline character
    let newlineAttributedString = NSAttributedString(string: "\n")
    mutableAttributedString.append(newlineAttributedString)
}

textView.attributedText = mutableAttributedString
view.addSubview(textView)


PlaygroundPage.current.liveView = view

1 个答案:

答案 0 :(得分:0)

我找到了原因,newlineAttributedString还需要NSFontAttributeName

let newlineAttributedString = NSAttributedString(string: "\n", attributes: [
    NSFontAttributeName: bodyFont
])
mutableAttributedString.appendAttributedString(newlineAttributedString)