swiftswiftui

Repeated pattern image as background in SwiftUI?


I'm trying to set an image as background and repeat it throughout the screen. In UIKit it is as simple as this single line of code:

view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))

Is there an equivalent in SwiftUI?

var body: some View {
  HStack {
    VStack {
      Spacer()
    }
    Spacer()
  }
  .background(
    Image("background") // Need this pattern image repeated throughout the page
  )
}

Solution

  • The easiest way is to use the resizable modifier and set the resizing mode to Image.ResizingMode.tile.

    Image("background")
        .resizable(resizingMode: .tile)