如何在 SwiftUI 中为单行文本设置行高? [英] How to set line height for a single line text in SwiftUI?
本文介绍了如何在 SwiftUI 中为单行文本设置行高?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我一直在使用 .lineSpacing(...)
,但这只适用于多行文本.
Currently, I have been using .lineSpacing(...)
, but this only works for multi-line text.
/// Sets the amount of space between lines of text in this view.
///
/// - Parameter lineSpacing: The amount of space between the bottom of one
/// line and the top of the next line.
@inlinable public func lineSpacing(_ lineSpacing: CGFloat) -> some View
这意味着我很难准确地从草图/figma 翻译字体,我需要调整填充以使其正确.下面是一个示例:
What this means is that it's harder for me to translate fonts exactly from sketch/figma, and I need to play around with the padding to get it right. Here is an example that shows this:
VStack {
// Line spacing is ignored.
Text("Hello, World!")
.background(Color.green)
.lineSpacing(50)
Spacer()
// Line spacing is correct.
Text("Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.")
.background(Color.green)
.lineSpacing(50)
}
推荐答案
基于 Dan Hassan 的回答我给自己做了一个 ViewModifier 来做到这一点,看起来它按预期工作
Based on the answer by Dan Hassan I made myself a ViewModifier to do this, and it looks like it works as intended
import SwiftUI
struct FontWithLineHeight: ViewModifier {
let font: UIFont
let lineHeight: CGFloat
func body(content: Content) -> some View {
content
.font(Font(font))
.lineSpacing(lineHeight - font.lineHeight)
.padding(.vertical, (lineHeight - font.lineHeight) / 2)
}
}
extension View {
func fontWithLineHeight(font: UIFont, lineHeight: CGFloat) -> some View {
ModifiedContent(content: self, modifier: FontWithLineHeight(font: font, lineHeight: lineHeight))
}
}
这篇关于如何在 SwiftUI 中为单行文本设置行高?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文