在我的第一个示例中,我将文本放置在屏幕上的特定位置.在第二个示例中,当我添加更多字符时,文本在上下两个方向上的高度都会增加.有没有什么办法让文本视图增加高度,但只影响视图的底部?

First Example enter image description here

Second Example enter image description here

以下是此文本视图的代码.

import SwiftUI

struct ContentView: View {
    var body: some View {
        // ZStack is used for a background color
        ZStack {
            Color.teal.opacity(0.3)
                .ignoresSafeArea()
            GeometryReader { proxy in
                Image(.snareDrum)
                    .resizable()
                    .scaledToFit()
                    .frame(width: proxy.size.width * 0.80, height: proxy.size.height * 0.80)
                    .background {
                        Color.white
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            Text("Lorem ipsum dolor, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Praesent tristique magna sit amet purus.")
                .lineLimit(nil)
                .multilineTextAlignment(.center)
                .frame(width: 200)
                .fixedSize(horizontal: false, vertical: true)
                .background(.red)
                .position(x: 195, y: 210)
        }
    }
}

#Preview {
    ContentView()
}

推荐答案

这是因为ZStack的默认对齐方式是center,您应该将其转换为topLeading,即(0, 0),并使用类似offset的命令将文本移动到您需要的位置:

ZStack(alignment: .topLeading) {  // 👈 add this
    ,,,

    Text("Lorem ipsum dolor, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Praesent tristique magna sit amet purus.")
        .lineLimit(nil)
        .multilineTextAlignment(.center)
        .frame(width: 200)
        .fixedSize(horizontal: false, vertical: true)
        .background(.red)
        .offset(x: 195, y: 210) // 👈 use this
//        .position(x: 195, y: 210) // 👈 remove this
}

Swift相关问答推荐

从`compactMap()`闭包返回`nil`未通过结果类型判断

将变量设置为 @Published 会 destruct 代码而不会出现任何错误

try 从闭包访问返回的字符串时出现无法将类型 '()' 的返回表达式转换为返回类型 'String'编译器错误

是否可以限制 ExpressibleByIntegerLiteral struct 的初始值?

如何在设备(或常量)地址空间中创建缓冲区?

为什么这段Swift读写锁代码会导致死锁?

Swift Property Wrappers-Initialization 失败并显示无法将‘Double’类型的值转换为预期的参数类型

防止带有背景的文本扩展到 maxWidth

如何将变量添加到不属于可解码部分的 struct ?

Swift并发:为什么不在其他后台线程上执行任务

如何为 Swift UI 视图定义 struct ?

如何从另一个 swift 文件中调用函数

如何在 SwiftUI 中通过按钮点击一次为一个更改设置动画?

Apple 的自然语言 API 返回意外结果

AVPlayer 在 iOS 15.4 中寻求 completionHandler 返回 false

通用枚举菜单 SwiftUI

Swift 2 中的新 @convention(c):我该如何使用它?

playground 导入:没有这样的模块Foo

在 Swift 中从服务器播放视频文件

通过单击表格视图中的单元格打开新的视图控制器 - Swift iOS