iOS 13 : How can I tweak the leading/descend/line height of a custom font in UIKit/SwiftUI

标签 ios swift fonts uikit uifont

我正在使用自定义字体,不知何故渲染搞砸了行高,可能是因为配置错误 descentleading (?),以便 g 和 j 在渲染文本的最后一行被截断。我认为这可能是这种特定字体的问题,因为 Sketch 也暴露了相关字体的类似问题,但我觉得我对排版测量或字体的了解还不够。我在 Typographic Concepts 上找到了这个 Apple 文档页面很有见地。
Rendered Label exposing the cut off
我使用 FontLab 的测试版本查看了字体本身,顺便说一句,这是我第一次使用的 - 所以我几乎不知道我在看什么。看起来 g 确实低于配置的 descent ,这似乎是最后一行的内容。 (?)(见:Character view in FontLab, showing the descend of the g)
通过 lineSpacing我可以调整线条本身之间的距离以在前几行中解决这个问题。我知道 iOS 14 将带来一种方法来修改 leading Text在 SwiftUI 中。但我需要针对 iOS 13,所以这无济于事。
我也试过 SwiftUI 的 Text , 正常 UILabel.textUILabel.attributedText使用自定义的段落样式,但我在那里调整的任何内容似乎都无法缓解问题。
View 甚至没有剪辑。只是向框架添加填充根本没有帮助。它增加了距离,但 g 和 j 仍然被切断。
我能做什么?子类 UILabel并覆盖 intrinsicContentSize添加一些额外的空间,当最后一行有 g 和 j 时?感觉 a) 脏 b) 考虑到填充没有帮助,它可能无法解决问题?
字体本身是这里的问题吗?我可以以某种方式修补字体而不会使它变得更糟吗?
当我使用较低级别的 API 时,有什么方法可以修改字体的前导或下降高度?似乎我可以转到 CoreText,如 CTFontCreateCopyWithAttributes(_:_:_:_:)是候选人,如果我可以通过属性修改前导、行距或下降?可以或猴子补丁/swizzle 东西而不会射中自己的膝盖吗?我应该向雷达提交反馈吗?

最佳答案

您需要使用 NSAttributedString而不是 String 来控制 UILabel 的行距。这是示例代码

let style = NSMutableParagraphStyle()
style.lineSpacing = 20
let string  = NSMutableAttributedString(string: "The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog")
string.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, string.length))
let label = UILabel(frame: CGRect(x: 20, y: 100, width: 300, height: 500))
label.attributedText = string
label.numberOfLines = 0
self.view.addSubview(label)
输出
enter image description here

关于iOS 13 : How can I tweak the leading/descend/line height of a custom font in UIKit/SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63622822/

相关文章:

ios - iPad : need accurate alternative to NSTimer for making donkey kong style game

iOS 如何在使用 AVAssetWriter 捕获视频时正确处理方向

python - 我需要在 Python IDLE 中使用更大的字体

c++ - Win32下如何初始化Pango?

ios - NSAttributedString 报告 UITextView sizeThatFits 和 boundingRectWithSize 的大小不正确,并设置了正确的选项

ios - iOS 沙盒 Game Center 排行榜是否会转移到真正的 Game Center?

ios - 无法将 View 推送到 searchResultsController

ios - 如何在 Xamarin ios 中获取导航栏后退按钮的大小?

swift - 展开/合并多级可选

ios - 向项目添加自定义字体但是当我尝试使用它们时我得到一个 "fatal error: unexpectedly found nil while unwrapping an Optional value"