我很难找到一种解决办法来将105 TextFieldHStack中的另一个Text对齐.我想把它排成firstTextBaseline排.问题是,当TextField的文本变为空,并且只显示占位符时,TextField会向下跳转.

我在List行中使用了这HStack行,但即使在这样的剥离和简化代码中,对齐也不起作用:

struct TextFieldAlignmentProblem: View {
    
    @State private var text: String = ""
    
    var body: some View {
        HStack(alignment: .firstTextBaseline) {
            Text("1")
            TextField("Text", text: $text, axis: .vertical)
        }
        .padding()
    }
}

TextField jumps down when its text becomes empty and only the placeholder is shown.

如果我删除axis: .vertical或使用.center对齐而不是.firstTextBaseline, skip 问题就消失了,但这不是我需要的布局.

这个问题看起来很简单,但我目前找不到合适的解决方案.

推荐答案

不幸的是,这是一个错误,发生在axis: .vertical号公路上时,该字段为空.

✅完美解决方案:

您可以创建一个占位符来将文本字段保持在正确的位置:

struct TextFieldAlignmentProblem: View {

    @State private var text: String = ""
    private var placeholder: String { text.isEmpty ? " " : text } // 👈 Generate a correct placeholder. I have used a single space.

    var body: some View {
        HStack(alignment: .firstTextBaseline) {
            Text("1")

            TextField("Text", text: .constant(placeholder), axis: .vertical) // 👈 Use the placeholder as the base
                .opacity(0) // 👈 Make it hidden keeping the frame
                .overlay { // 👈 Put the actual TextField on top of the placeholder view
                    TextField("Text", text: $text, axis: .vertical)
                }
        }
        .padding()
    }
}

💡简单的解决方案:

如果您不打算使用不同的字体、字样、动态类型等,一个非常简单快速的解决方法可能是判断条件并传递(视觉上)正确的对齐方式:

HStack(
    alignment: text.isEmpty ? .center : .firstTextBaseline // 👈 Conditional alignment
) { ,,, }

Ios相关问答推荐

缺少预期的键:';NSPrival yCollectedDataTypes';

我想在expo 中使用useSafeAreaInsets来获取paddingbottom,但我得到了一个错误

在许多UIButton中对齐文本,即使SF Symbols(或其他图像)具有不同的宽度?

在SwiftUI中插入绘制重复形状

如何在SwiftUI中顺时针和逆时针两个方向应用旋转效果?

SWIFT-仅解码感兴趣的元素

使用 Objective-C 创建 iOS 框架

Swift UI中如何为Text提供内部填充

Swift Combine:prepend() before share() 阻止初始接收器执行

Task.cancel() 的 TaskPriority 的区别

占位符文本未显示在 TextEditor 上

iOS按钮和navigationLink在List中相邻

SwiftUI Disclosure Group 文本对齐

在 SwiftUI 中打开 PDF

clipShape swift的三元

使用 AVAudioPlayer 播放声音

向标签栏控制器添加新标签

iOS Swift - 获取当前本地时间和日期时间戳

UITextView 从文本的底部或中间开始

Objective-C 将 NSDate 设置为当前 UTC