gpt4 book ai didi

ios - 为什么在使用 TextKit 呈现文本时第二行最终会比第一行短?

转载 作者:行者123 更新时间:2023-11-29 00:51:14 25 4
gpt4 key购买 nike

示例项目:http://d.pr/f/1coXu

我正在使用 TextKit 将一些文本呈现为本质上是 UILabel 的非常基本的再创造。代码非常简单,在这个例子中只是将硬编码的 NSAttributedString 绘制到 View 本身:

class TextKitView: UIView {
// TextKit Objects
var textStorage: NSTextStorage!
var textContainer: NSTextContainer!
var layoutManager: NSLayoutManager!

override init(frame: CGRect) {
super.init(frame: frame)

backgroundColor = UIColor.clearColor()

layoutManager = NSLayoutManager()

textStorage = NSTextStorage(attributedString: createAttributedString())
textStorage.addLayoutManager(layoutManager)

textContainer = NSTextContainer(size: CGSize(width: bounds.width, height: bounds.height))
layoutManager.addTextContainer(textContainer)
}

required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

override func drawRect(rect: CGRect) {
let glyphRange = layoutManager.glyphRangeForTextContainer(textContainer)
layoutManager.drawBackgroundForGlyphRange(glyphRange, atPoint: bounds.origin)
layoutManager.drawGlyphsForGlyphRange(glyphRange, atPoint: bounds.origin)
}

private func createAttributedString() -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: "Test string for testing", attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(16.0)])

let labelAttributedString = NSAttributedString(string: "Foo bar\n testing", attributes: [NSForegroundColorAttributeName: UIColor.darkGrayColor(), NSBackgroundColorAttributeName: UIColor(white: 0.95, alpha: 1.0)])
attributedString.appendAttributedString(labelAttributedString)

return attributedString
}
}

但是,当我创建 View 时:

override func viewDidLoad() {
super.viewDidLoad()

let textKitView = TextKitView(frame: CGRect(x: 0.0, y: 100.0, width: 320.0, height: 320.0))
view.addSubview(textKitView)
}

最终看起来像这样:

enter image description here

由于某种莫名其妙的原因,你可以看到第二行的背景颜色和高度明显短于第一行,这看起来很奇怪。

如何防止这种情况发生?这是什么原因造成的?如果我使用 UILabel 并提供相同的属性字符串,则两行的高度相同。如果有帮助,我在上面附上了一个非常小的示例项目。

最佳答案

查看 NSParagraphStyle:https://developer.apple.com/reference/uikit/nsparagraphstyle

该类有行高属性,即 minimumLineHeightmaximumLineHeight 可以完成您想要做的事情。您可以像这样为 NSAttributedString 设置段落样式:

let paraStyle = NSMutableParagraphStyle()
paraStyle.setParagraphStyle = NSParagraphStyle.default
paraStyle.minimumLineHeight = 50 // for example
attributedString.addAttribute(NSParagraphStyleName, value: paraStyle, range:NSMakeRange(0, attributedString.length))

关于ios - 为什么在使用 TextKit 呈现文本时第二行最终会比第一行短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com