Home > other >  How to put different View into a List?
How to put different View into a List?

Time:11-17

I new come to Xcode,

here is my code

struct ContentView: View {
var body: some View {
        NavigationView {
            List {
                TestView().padding();
                TestView2().padding();
                TestView3().padding();
                TestView4().padding();
                  }
            .navigationBarTitle(Text("Place"))
            .navigationBarItems(trailing: EditButton())
              }
    }
}

one of the Testview:

struct TestView: View {
@Environment(\.editMode) var mode

@State var timeNow = ""
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var dateFormatter: DateFormatter {
    let fmtr = DateFormatter()
    fmtr.dateFormat = "LLLL dd, HH:mm"
    fmtr.timeZone = TimeZone(identifier:  "Asia/Hong_Kong")!
    return fmtr
}

var body: some View {
   
    Text("HK: "   timeNow)
        .onReceive(timer) { _ in
            self.timeNow = dateFormatter.string(from: Date())
        }

}}

My preview

I want to "Press the Edit button, then I can delete different place's clock"

I read the tutorial on the internet,if want to delete "something", it should put "something" into the "List.

However, in Xcode, "View" is not variable or int or string, how can I put the different view into "List" and call it out or delete.

Or any other way to accomplish my purpose?

My final goal is: to press the "edit Button", and choose to delete a different place.

Future, i want to add another function, press " button" then can choose the different place and add to display.

CodePudding user response:

struct ContentView: View {
    @State var locations: [String] = ["Asia/Hong_Kong"] // you can add additional location strings
    @State var isEditMode: EditMode = .inactive
    var body: some View {

        NavigationView {
            List {
                ForEach(locations, id: \.self) { location in
                    TestView(location: location)
                }
            }
            .navigationBarTitle(Text("Place"))
            .navigationBarItems(trailing: EditButton())
            .environment(\.editMode, self.$isEditMode)
        }
    }
}
    struct TestView: View {
        let location: String
        @State var timeNow = ""
        let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
        var dateFormatter: DateFormatter {
            let fmtr = DateFormatter()
            fmtr.dateFormat = "LLLL dd, HH:mm"
            fmtr.timeZone = TimeZone(identifier:  location)!
            return fmtr
        }
        var body: some View {
            Text("HK: "   timeNow)
                .onReceive(timer) { _ in
                    self.timeNow = dateFormatter.string(from: Date())
                }
        }
    }

This will be work.
  • Related