Search code examples
swiftswiftuibackgroundswiftui-form

How can I put the Image in the background of a Form in SwiftUI?


I'm currently working on an app and I wonder how to insert an image as a background of a Form in SwiftUI.

I have already tried this:

.onAppear {
   UITableView.appearance().backgroundView = UIImageView(image: UIImage(named: "Background"))  
}

First, it seemed to work, but when I pressed one of the multiple NavigationLinks that has the Form, the App crashes. Thanks!


Solution

  • You need to clear both the UITableView and the UITableViewCell appearance:

    UITableView.appearance().backgroundColor = UIColor.clear
    UITableViewCell.appearance().backgroundColor = UIColor.clear
    

    Then, you can change the background as you wish:

    struct ContentView: View {
        init() {
            UITableView.appearance().backgroundColor = UIColor.clear
            UITableViewCell.appearance().backgroundColor = UIColor.clear
        }
    
        var body: some View {
            Form {
                Text("Item!")
                    .listRowBackground(Color.clear)
            }
            .background(
                Image("Background")
            )
        }
    }
    

    (You also need .listRowBackground if you want to change the row background.)