在Swift UI中

我正在使用类似于卡片的视图,我很想知道容纳元素的最小高度,然后在其周围添加边框。

这变得很困难,因为VStack和HStack似乎要占用尽可能多的空间,因此我需要手动插入.frame(...)来强制执行此操作,但这使它变得非常不灵活。

在图片中,我突出显示了VStack,正如您所看到的那样,该像素超出了48px帧高的限制。

代码

var body: some View {
    HStack(spacing: 0) {
      Image("cocktail")
        .resizable()
        .scaledToFit()
        .padding(Size.Spacing.unit * 2)
        .background(self.color)
        .cornerRadius(8)
        .overlay(
          RoundedRectangle(cornerRadius: 8)
            .stroke(self.color)
      )


      HStack(spacing: 0) {
        VStack(alignment: .leading) {
          Text("Negroni").font(.headline)
          Spacer()
          HStack {
            Tag(name: "bitter")
            Tag(name: "sweet")
            Tag(name: "strong")
          }
        }
        .padding(.leading,10)
        Spacer()
      }
    }
    .padding(Size.Spacing.unit * 2)
    .frame(height: 48.0)
  }

在Swift UI中

iCMS 回答:在Swift UI中

也许我误解了您,但是我尝试了您的示例...不幸的是,它不是可编译的,因此我不得不更改某些内容。但是如您所见,结果(vstack-黄色)占用的空间不足,可能是因为您的填充了吗?

struct ContentView: View {
    var body: some View {
      HStack(spacing: 0) {
        Image("cocktail")
          .resizable()
          .scaledToFit()
      //    .padding(Size.Spacing.unit * 2)
            .background(Color.blue)
          .cornerRadius(8)
          .overlay(
            RoundedRectangle(cornerRadius: 8)
                .stroke(Color.yellow)
        )


        HStack(spacing: 0) {
          VStack(alignment: .leading) {
            Text("Negroni").font(.headline)
            Spacer()
            HStack {
              Text("bitter")
              Text("sweet")
              Text("strong")
            }
          }
          .background(Color.yellow)
          .padding(.leading,10)
          Spacer()
        }.background(Color.red)
      }
   //   .padding(Size.Spacing.unit * 2)
      .frame(height: 48.0)
    }
}

enter image description here

,

因为VStack和HStack似乎要占用尽可能多的空间

这种假设是不正确的-默认情况下,堆栈紧紧地容纳内容,而内容紧紧地限制到最小,并且UI元素之间使用默认填充。在提供的代码中,Spacer()有责任扩展到最大可用空间。因此,为了使内容空间最小化,突出显示的VStack应该进行如下更改:

VStack(spacing: 0,alignment: .leading) {
  Text("Negroni").font(.headline)
  HStack {
    Tag(name: "bitter")
    Tag(name: "sweet")
    Tag(name: "strong")
  }
}
本文链接:https://www.f2er.com/2182113.html

大家都在问