Search code examples
xcodeswiftuiapple-watchwatchos

Placing image to the left of text inside list


I have the following code that currently gives me the following errors:

enter image description here

The code is:

import SwiftUI

struct EmailList: Identifiable {
    var img: Image
    var id: String
    var isOn = false
}

struct ContentView: View {
    @State var lists = [
        EmailList(img: Image(systemName: "car.fill"), id: "Monthly Updates", isOn: true),
        EmailList(img: Image(systemName: "car.fill"), id: "News Flashes", isOn: false),
        EmailList(img: Image(systemName: "car.fill"), id: "Special Offers", isOn: true)
    ]
    
    
    var body: some View {
        Form {
            Section {
                ForEach($lists) { $list in
                    Toggle(list.img, list.id, isOn: $list.isOn)
                }
            }            
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Which produces something like this on the watch:

enter image description here

I'm not exactly sure what it is saying/wanting me to do. Most of the examples I've seen have been in this type of format so I'm not sure if that's because it was an app just for the iPhone or something else.

All of the variables are filled out along with its class to define an image as the first parameter's, then the name (id) and last the true or false.

My goal in all of this is to have it look like this:

enter image description here


Solution

  • You can achieve this using a Label for your Toggle's label, e.g.

    struct ContentView: View {
        @State var lists = [
            EmailList(img: Image(systemName: "car.fill"), id: "Monthly Updates", isOn: true),
            EmailList(img: Image(systemName: "car.fill"), id: "News Flashes", isOn: false),
            EmailList(img: Image(systemName: "car.fill"), id: "Special Offers", isOn: true)
        ]
        
        
        var body: some View {
            Form {
                Section {
                    ForEach($lists) { $list in
                        Toggle(isOn: $list.isOn) {
                            Label {
                                Text(list.id)
                            } icon: {
                                list.img
                            }
                        }
                    }
                }
            }
        }
    }
    

    enter image description here