M Reza
M Reza

Reputation: 19708

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
  )
}

Upvotes: 10

Views: 6148

Answers (2)

Sebastian
Sebastian

Reputation: 133

Old thread, but since this thread shows up high in a Google search and since .resizable(resizingMode: .tile) won't work with system symbols, starting with iOS 15 we can do the following:

struct ContentView: View {
    var body: some View {
        Rectangle()
            .foregroundStyle(.image(
                Image(systemName: "questionmark.circle")
            ))
            .font(.system(size: 50))
    }
}

Background of tiled image with system symbol Full credit to this blog post I've found: https://fatbobman.com/en/posts/how-to-tile-images-in-swiftui/

Upvotes: 0

Marcio
Marcio

Reputation: 2107

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

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

Upvotes: 39

Related Questions