In SwiftUI, is it possible to use a modifier only for a certain os target?

前端 未结 4 1682
無奈伤痛
無奈伤痛 2021-01-12 12:16

Good day! In SwiftUI, is it possible to use a modifier only for a certain os target? In the following code I would like to use the modifier .listStyle(SidebarListStyle()) on

4条回答
  •  盖世英雄少女心
    2021-01-12 13:00

    Thanks DoesData for giving me the direction.

    The solution was to use #is os(macOS) around the entire code and not only around the modifier itself.

    import SwiftUI
    
    struct ContentView: View {
    
      @State var selection: Int?
    
      var body: some View {
    
        #if os(macOS)
        HStack() {
          NavigationView {
            List () {
              NavigationLink(destination: FirstView(), tag: 0, selection: self.$selection) {
                Text("Click Me To Display The First View")
              } // End Navigation Link
    
              NavigationLink(destination: SecondView(), tag: 1, selection: self.$selection) {
                Text("Click Me To Display The Second View")
              } // End Navigation Link
    
            } // End list
              .frame(minWidth: 350, maxWidth: 350)
              .onAppear {
                self.selection = 0
            }
    
          } // End NavigationView
            .listStyle(SidebarListStyle())
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        } // End HStack
    
        #elseif os(iOS)
        HStack() {
          NavigationView {
            List () {
              NavigationLink(destination: FirstView(), tag: 0, selection: self.$selection) {
                Text("Click Me To Display The First View")
              } // End Navigation Link
    
              NavigationLink(destination: SecondView(), tag: 1, selection: self.$selection) {
                Text("Click Me To Display The Second View")
              } // End Navigation Link
    
            } // End list
              .frame(minWidth: 350, maxWidth: 350)
              .onAppear {
                self.selection = 0
            }
    
          } // End NavigationView
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        } // End HStack
        #endif
    
      } // End some View
    } // End ContentView
    
    struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
        ContentView()
      }
    }
    

提交回复
热议问题