swift 向VStack左侧添加边框

osh3o9ms  于 2022-12-10  发布在  Swift
关注(0)|答案(2)|浏览(239)

我的SwiftUI视图如下所示:

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack(alignment: .top) {
            VStack(alignment: .leading) {
                HStack {
                    Image(systemName: "star.fill")
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 16, height: 16)
                    Text("Speed")
                }.padding(.bottom, 10)
                
                HStack {
                    Image(systemName: "star.fill")
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 16, height: 16)
                    Text("Distance")
                }
                Spacer()
            }
            Spacer()
        }
    }
}

在预览中看起来如下所示。

我想在包含TextImageVStack中添加一条黑线左边的边框。
有人知道如何在SwiftUI中做到这一点吗?

62o28rlo

62o28rlo1#

正如我在评论中提到的,现有的解决方案为您提供了一些很好的选择。一个真正 *hacky的方法 * 是这样的:

struct ContentView: View {
    
    var body: some View {
        // This is a wrapper, mostly hidden except for left side
        ZStack {
            contentView
                .background(Color.white) // hide the rest of black frame
                .padding(.leading, 10) // width of "border"
        }
        .ignoresSafeArea()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
    }
    
    // This is your original view
    var contentView: some View {
        
        HStack(alignment: .top) {
            VStack(alignment: .leading) {
                HStack {
                    Image(systemName: "star.fill")
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 16, height: 16)
                    Text("Speed")
                }.padding(.bottom, 10)
                
                HStack {
                    Image(systemName: "star.fill")
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 16, height: 16)
                    Text("Distance")
                }
                Spacer()
            }
            Spacer()
        }
    }
}
zte4gxcn

zte4gxcn2#

对于我来说,我实际上会像这样编写代码来获得视图:

struct Sample: View {
   var body: some View {
       HStack {
           VStack(alignment: .leading) {
               ForEach(0..<5, id: \.self) { _ in
                   HStack {
                       Image(systemName: "star.fill")
                       Text("Speed")
                       Spacer()
                   }
                   .background(leftBorder)
               }
           }
           .padding(.leading)
       }
   }

   var leftBorder: some View {
       HStack {
           Rectangle()
               .frame(width: 1)
        
           Spacer()
       }
    }
}

结果:

但我不确定这是不是你想要的,但如果这能帮上忙,我很高兴。

相关问题