2

I have a swift file with a few stacks, of which the upper text acts weirdly. I can't understand why the background color of the "controller"-text extends up to the end of the screen. How can I adjust the height of the background?

 var body: some View {
        NavigationView {
            ZStack {
                Color("Themecolor")
                .edgesIgnoringSafeArea(.all)
                VStack {
                    HStack(spacing: 0) {
                      Text("BIKE")
                        .font(.system(size: 52))
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                      Text("Controller")
                        .font(.system(size: 52))
                        .foregroundColor(.black)
                        .background(
                            .white)
                    }
                    .offset(y: -50)
                    

enter image description here

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
davmel
  • 65
  • 5
  • [swiftui-how-do-i-change-the-background-color-of-a-view](https://stackoverflow.com/questions/56437036/swiftui-how-do-i-change-the-background-color-of-a-view) – Mohamad Ghaith Alzin May 27 '22 at 16:45
  • Welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour) and see: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example (MRE)](https://stackoverflow.com/help/minimal-reproducible-example). The problem is not reproducible from the code posted. Please post an actual MRE that shows the problem. Please do not use custom colors or any custom elements without including the code for them. The simplest way to vaerify this is to make a new project and edit the code in there. – Yrb May 27 '22 at 16:49

1 Answers1

1

By default new background modifier with style is applied with ignoring safe area for .all, so we can explicitly turn it off, like

  Text("Controller")
    .font(.system(size: 52))
    .foregroundColor(.black)
    .background(
        .white, ignoresSafeAreaEdges: .bottom)  // << here !!

demo

Tested with Xcode 13.4 / iOS 15.5

Alternate: for backward compatibility is to use different variant of modifier

  Text("Controller")
    .font(.system(size: 52))
    .foregroundColor(.black)
    .background(
        Rectangle().fill(.white))    // << here !!
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • works perfectly! Thank you! do you know how to adjust the height of it? so that the white background is shorter? – davmel May 27 '22 at 16:54
  • Well, it is exactly by Text's frame, so it is possible to *fix* using some hardcoded padding, like `Rectangle().fill(.white).padding(.vertical, 10)` – Asperi May 27 '22 at 17:00