4

I'm trying to give my ListView a background image which should not be for every cell. So only one image for the whole view. I have tried to add .background(Image("nameOfImage)) as list modifier but did not do anything.

NavigationView {
    List(elements) { element in 
        NavigationLink(destination: NextView) {
            Text(element.name)
            Image(element.image)
        }
    }.background(Image("nameOfImage"))
}

I have also tried a ZStack but I think the list overlays my image

So how can I put an image as list background or view background (the code above is the whole view)

Uni_x
  • 326
  • 2
  • 14
  • If this is for macOS the post [SwiftUI background color of List Mac OS](https://stackoverflow.com/a/60467330/12299030) can be helpful. – Asperi Apr 25 '20 at 14:17

1 Answers1

5

It did the thing, but the point is that UITableView and UITableViewCell have default white backgroundColor. You should make them transparent to see through.

Something like:

struct ContentView: View {

    init() {
        UITableView.appearance().backgroundColor = .clear // For tableView
        UITableViewCell.appearance().backgroundColor = .clear // For tableViewCell
    }

    var body: some View {
        NavigationView {
            List(0...10, id: \.self) { number in
                Text("\(number)")
            }.background(Image("BG"))
        }
    }
}

Note that I have simplified my answer to make it independent from other parts of your project

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • 1
    thank you but as I'm still a beginner in iOS programming I tried it like you did. But this created two errors which I couldn't remove: `Closure containing a declaration cannot be used with function builder 'ViewBuilder'` and `Initializers may only be declared within a type` – Uni_x Apr 25 '20 at 15:04
  • Sorry my bad. I’m on the mobile and It’s kind of hard to write code here :) I have updated mu answer – Mojtaba Hosseini Apr 25 '20 at 15:13
  • I have tried it too before you showed me but I'm getting another error: `Return from initializer without initializing all stored properties` Can you help me again? Don't get it – Uni_x Apr 25 '20 at 18:02
  • That is not related to the question my friend. You probably forgot to assign value to all of your stored properties. I have simplified my answer to make it independent from other parts of your project and make it a working example. – Mojtaba Hosseini Apr 25 '20 at 18:37
  • 1
    This has been driving me crazy for three days. I've searched everywhere. Seems a lot harder than it should be. How many would think of turning off UI... Thank you for you answer. – user1204493 Jul 23 '20 at 22:39
  • Typical swiftui, nothing works or it's changed or everything's outdated. Something so simple is so frustrating – user2619824 Mar 11 '23 at 05:19