SwiftUI 用图像包装 HStack [英] SwiftUI Wrapping HStack with Images

查看:28
本文介绍了SwiftUI 用图像包装 HStack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个包含 x 个图像的 HStack,并将以包装 HStack 的方式显示它们(即,如果 7 个图像中只有 4 个适合该行,则将剩余的 3 个溢出到下一行).

我正在尝试使用库 WrappingHStack (

I am trying to make a HStack which contains x number of images and will display them in a wrapping HStack manner (i.e if only 4 of the 7 images fit on the line, then spill the 3 remaining over onto the next line).

I am trying to use the library WrappingHStack (https://github.com/dkk/WrappingHStack) but the result isn't as expected, the images are not wrapping around.

Here is my code:

    @State var numEarths : Int = 7;
    var body: some View {
        VStack{
        
            Text("If everyone were to live like you, we would need \(numEarths) Earths").font(.title)
            WrappingHStack{
                ForEach(0 ..< numEarths){_ in
                Image("logo")
                
                }
             }
         }
    }

Here is the result on the simulator (see, no wrapping)...we should see 7 Earth logo images but you can only see 4 (and a tiny bit of number 5). screenshot of image

Please can someone help me fix this issue? I am new to SwiftUI dev so please go lightly on me if this is a silly mistake. Thanks.

解决方案

According to the WrappingHStack library, if you want to achieve what you above-mentioned, you need to do two things:

  • Give your Image a frame so that the WrappingHStack can know how many elements to put in per line.
  • Change your ForEach loop to WrappingHStack, because WrappingHStack can be used as a ForEach to loop over items.

WrappingHStack(0..<numEarths, id:\.self) { _ in
    Image("logo")
        .resizable()
        .frame(width: 100, height: 100)
}

这篇关于SwiftUI 用图像包装 HStack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆