Skip to Content

How to set background in SwiftUI?

SwiftUI provides several ways to customize the background of views in your app. The background can be a solid color, an image, or even a graphical gradient. Setting the right background is important for aesthetics and can also provide visual cues to help users understand different sections of your app.

Setting a Solid Color Background

The simplest way to set a background is with a solid color. SwiftUI includes a .background() modifier that accepts a Color value:


Text("Hello World!")
  .background(Color.blue)

You can use the built-in Color options like .blue, .red, and .green. Or create custom colors using the init(red:green:blue:) initializer:


Text("Custom color")
  .background(Color(red: 0.9, green: 0.8, blue: 0.2)) 

The background color will be applied to the frame of the current view. If you want the background of the parent view instead, use .background(in:)


Text("Blue text")
  .background(in: Color.blue)

Using an Image Background

You can also set a view’s background to an image, like a photo. Use the .background() modifier and pass in an Image instance:


Text("Image background")
  .background(Image("example"))

Make sure the image name matches the file in your asset catalog. The image will tile to fill the background by default. To resize or center the image instead, combine it with .resizable() and other modifiers:


Text("Resized image")
  .background(
    Image("example")
      .resizable()
      .aspectRatio(contentMode: .fill)
  )

You can even set the background to a nested stack of views, like combining an image with a tinted overlay color:


Text("Overlay")
  .background{
    Image("example")
    Color.black.opacity(0.5)
  }

Gradients

For more advanced backgrounds, you can create gradient effects using the AngularGradient and RadialGradient types. Here is a linear gradient from purple to pink:


AngularGradient(
  gradient: Gradient(colors: [.purple, .pink]),
  center: .center,
  startAngle: .degrees(0),
  endAngle: .degrees(360)
)

And a radial gradient centered in the middle:

 
RadialGradient(
  gradient: Gradient(colors: [.blue, .black]),
  center: .center,
  startRadius: 20,
  endRadius: 200
)

Set these gradient views as the background to get some nice effects. Gradients can make for great backgrounds that stand out.

Background Reader

Sometimes you need to dynamically set a background based on some external value. For example, having the background match the current time of day. SwiftUI includes a special BackgroundReader view for this:


BackgroundReader { proxy in
   let date = Date()
   let hour = Calendar.current.component(.hour, from: date)
   let background = hour > 6 && hour 

The BackgroundReader provides the proxy value which lets you examine properties like the bounds size to help construct your customized background view.

Background Spacer

When building custom backgrounds, you may notice unused blank space around your content. The background modifiers stretch the background view to fill the available space.

Use BackgroundSpacer to avoid this problem. It expands a background view to fill the remaining space:


VStack {
  Text("Hello")
}
.background(
  Color.green
    .edgesIgnoringSafeArea(.all) 
    .backgroundSpacer() // fills blank space  
)

Background Groups

You can apply multiple background effects using background groups:


Text("Hello")
  .background(
    Group {
      Color.green
        
      Image("example")
        .resizable()
        .aspectRatio(contentMode: .fill)
      
      LinearGradient(...)) 
    }
  )

The views in the Group will layer to create a composite background.

Transparent Backgrounds

To set a fully transparent background, use Color.clear:


Text("Transparent")
  .background(Color.clear)

This can be useful for e.g. images you want to display with rounded corners but no background color.

You can also make a background semi-transparent with Color.clear and opacity:

 
Text("Semi-transparent")
  .background(Color.clear.opacity(0.5))

Background Modifier Order

When applying multiple background modifiers, the order can matter. Later modifiers layer on top of earlier ones. For example:


Text("Hello")
  .background(Color.green) 
  .background(Image("example"))

Here the image will display on top of the green color since it comes last. Reversing the order would make the green color overlay the image.

Shared Backgounds

You can reuse background styles across multiple views using extension properties:


extension View {
  var blueBackground: some View {
    self.background(Color.blue)
  }
}

Text("Hello")
  .blueBackground

Image("pic")
  .blueBackground

This helps you avoid duplicating backgrounds.

Animated Backgrounds

To animate changes to the background, store it in a state variable that you can update:


@State var background = Color.clear

VStack {
  Button("Change") {
     withAnimation {
       background = .red 
     }
  }
}
.background(background)

This will allow smooth animated transitions each time the background color changes.

ScrollView Reader

You can also create backgrounds that respond to scroll position using ScrollViewReader:


ScrollViewReader { proxy in
  ScrollView {
    Text("...") // long scrollable content
    
    Color.clear.preference(key: ScrollOffsetPreferenceKey.self, value: proxy.scrollOffset)
  }
}
.background(
  GeometryReader { geo in
    // Adjust background based on scroll offset
  }
)

This allows the background to animate as the user scrolls through content.

Conclusion

That covers the main ways to customize backgrounds in SwiftUI views. The possibilities are endless - you can create any background effect imaginable with the tools provided. A well designed background complements your content and enhances the overall user experience. Don't neglect the importance of backgrounds in your apps!

Here are some key points to remember:

  • Use .background() with Color, Image, and Gradients
  • Layer multiple backgrounds with Groups
  • Animate with state variables
  • Reuse backgrounds with extensions
  • Adapt to scroll position

With all of SwiftUI's background options and modifiers, you have complete control to create beautiful, engaging view backgrounds for your users.