gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:54:43 49 4
gpt4 key购买 nike

目前,我一直在使用.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

这意味着我很难准确地从草图/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)
}

最佳答案

基于 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))
}
}

关于ios - 如何在 SwiftUI 中为单行文本设置行高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61705184/

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