首页 > 解决方案 > 在 SwiftUI 中对齐视图的高度

问题描述

我有一个 SwiftUI 视图,它是HStack两个视图中的一个: 1. 一个简单的Text视图,它充当一种标签,并且始终是单行 2. 一个自定义 UIKit 视图,它UITextView具有很多自定义格式

我的愿望是限制高度UITextView以匹配Text视图的高度(单行,高度取决于系统字体等)。我已经尝试了很多方法来解决这个问题,但我似乎无法找到有效的方法。GeometryReader似乎只将父属性传递给孩子,但没有解决“兄弟”问题。

有什么想法或见解吗?

标签: swiftui

解决方案


这是可能布局的演示。使用 Xcode 11.4 / ISO 13.4 测试

演示

注意:添加只是为了演示和更好的可见性.border.padding重要的地方在评论中标注。MultilineTextView是一个简单的表示UITextView

struct DemoFixedToLabel: View {
    var body: some View {
        HStack {
            Text("Some Text").font(Font.system(.title))
                .padding()
                .border(Color.blue)
                .fixedSize()             // << here !!
            MultilineTextView(text: .constant("My desire is to restrict the height of the UITextView to match the height of the Text"))
                .border(Color.green)
        }
        .padding()
        .border(Color.red)
        .fixedSize(horizontal: false, vertical: true)    // << here !!
    }
}

推荐阅读