Adding 2 backgrounds within a Z and HStack?

Viewed 96

The color.red is my widgets main background but I would like to add a black background to the top behind the text "Line1" and image "2". So basically a black bar that stretches across the top under the text and image.

var body: some View {
    ZStack {
        Color.red
        
        VStack(alignment: .leading, spacing: 0) {
            HStack {
                Text("Line1")
                    .foregroundColor(.orange)
                    .bold()
                    .font(.system(size: 17.5))
                    .padding(.top)
                Spacer()
                
                Image("2")
                    .resizable()
                    .frame(width: 25, height: 25)
                    .padding(.top)
                
            }
            .padding(.horizontal)
            .border(Color.green)
            
            VStack(alignment: .leading) {
                Image("2")
                    .resizable()
                    .frame(width: 67, height: 30)
                
                Text("State")
                    .foregroundColor(Color.green)
                    .font(.system(size: 15))
                
                Text("1")
                    .foregroundColor(Color.blue)
                    .font(.system(size: 10))
                    .opacity(0.5)
                
                Spacer()
                Spacer()
            }
            .padding(.horizontal)
            .border(Color.blue)
        }
    }
}
1 Answers

You can add a .background modifier to your first HStack:

HStack {
    //content here             
}
.padding(.horizontal)
.border(Color.green)
.background(Color.black)

Keep in mind that order of modifiers is important, so if you put the background before the padding, the padding will not have that background color -- that's why I used it last.

Related