【问题标题】:How do I stretch a View to its parent frame with SwiftUI?如何使用 SwiftUI 将视图拉伸到其父框架?
【发布时间】:2019-06-17 11:40:27
【问题描述】:

在你下面看到图像和我想拉伸到红色边框的黑色方块。

我已经尝试了以下

import SwiftUI
struct ContentView : View {
    var body: some View {
        HStack(spacing: 1) {
            Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
            ScrollView {
                VStack {
                    ForEach(0..<5) { index in
                        Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
                    }
                }.relativeWidth(1)
            }
            Rectangle().foregroundColor(.red).frame(width:20)
        }
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View { ContentView() }
}
#endif

但结果是这样的:

【问题讨论】:

  • 相关(重复?):stackoverflow.com/q/56534772/1187415
  • 它似乎是重复的......对不起。 (..但是这个问题的措辞要简单得多来证明这个问题?)
  • @Rivera 没有。我已经接受了在这里有效的答案。此外,关于您链接到的那个问题,该问题的答案是我的答案,链接到此处的答案。

标签: swift swiftui


【解决方案1】:

您可以使用GeometryReader 并将您的 ScrollView 包装到其中并将内容宽度设置为几何体的宽度大小。一个GeometryReader

为其父布局返回一个灵活的首选尺寸。

所以您的代码将如下所示:

HStack(spacing: 1) {
     Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
     GeometryReader { geometry in
          ScrollView {
               VStack {
                    ForEach(0..<5) { index in
                         Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
                    }
                }.relativeWidth(1)
               .frame(width: geometry.size.width)
          }
     }
     Rectangle().foregroundColor(.red).frame(width:20)
}

【讨论】:

  • 这是否建立在您的终端上?也许如果您粘贴完整的代码编辑?如果我在示例中超过了这个,我会在HStack(spacing: 1) 得到构建错误
  • @iOSCalendarpatchthecode.com 抱歉,多了一个“}”:]
  • 好的,这行得通!但是为什么ヽ(ಠ_ಠ)ノ?这是修复错误的技巧吗?
  • @iOSCalendarpatchthecode.com 用更多细节更新了我的答案。
【解决方案2】:

在 SwiftUI 中修复 ScrollViews 宽度的另一个(不那么)丑陋的黑客:

ScrollView {
    // ...
    Divider().opacity(0)
}

【讨论】:

    【解决方案3】:

    以下内容也将为您提供您正在寻找的结果:

    HStack(spacing: 1) {
        Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
        ScrollView {
            VStack {
                ForEach(0..<5) { index in
                    Rectangle().frame(minHeight: 50)
                }
            }
        }
        Rectangle().foregroundColor(.red).frame(width:20)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 2012-12-22
      • 2014-04-09
      相关资源
      最近更新 更多