如何在 SwiftUI 中为单行文本设置行高?

Zor*_*ayr 4 iphone xcode ios swift swiftui

目前,我一直在使用.lineSpacing(...),但这仅适用于多行文本

/// 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
Run Code Online (Sandbox Code Playgroud)

这意味着我很难准确地从草图/figma 翻译字体,我需要调整填充以使其正确。这是一个示例,说明了这一点:

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)
}
Run Code Online (Sandbox Code Playgroud)

小智 17

为了让你的文字与figma相匹配,这最终对我有用。例如,如果您的 Figma 设计具有 16 pt 的特定字体,行高为 32 pt:

let font = UIFont(name: "SomeFont", size: 16)!
return Text("Some Text")
    .font(.custom("SomeFont", size: 16))
    .lineSpacing(32 - font.lineHeight)
    .padding(.vertical, (32 - font.lineHeight) / 2)
Run Code Online (Sandbox Code Playgroud)

为了获得准确的行距值,我们必须用字体固有的行高减去所需的行高,但正如您所指出的,这仅对多行文本有效,并且仅在行之间有效。我们仍然需要考虑文本的顶部和底部填充以匹配所需的行高,因此再次添加总行高减去字体的行高。

  • 仅当您需要_增加_行间距时,此功能才有效。如果你想让它压缩,它不起作用,而是尊重默认的行高。 (8认同)
  • 有没有办法设置负 lineSpacing 或更小的 lineHeight? (2认同)

ixa*_*any 10

Xcode 12

使用.leading()修改器调整行距。

Text("Hello\nworld").font(Font.body.leading(.tight))
Run Code Online (Sandbox Code Playgroud)

当前支持的值:.tight.standard.loose

来源:苹果文档


小智 9

根据Dan Hassan的回答,我为自己制作了一个 ViewModifier 来执行此操作,看起来它按预期工作

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))
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有人找到了负“.lineSpacing”的解决方案吗?好像如果你传入一个负数,它会被视为 0。 (4认同)