見出し画像

Swiftで行こう!--SwiftUI(Composing Complex Interfaces)

このチュートリアルは

Home.swift

CategoryRow.swift

2つのファイルを作ることを中心に構成されています。

Home.swiftの中の構造体struct(CategoryHome())を作ります。それをrootとして起動時に表示されるようにしています。(SceneDelegate.swift)

 if let windowScene = scene as? UIWindowScene {
           let window = UIWindow(windowScene: windowScene)
           window.rootViewController = UIHostingController(
               rootView: CategoryHome()
                   .environmentObject(UserData())
           )
           self.window = window
           window.makeKeyAndVisible()
       }

CategoryHome()でリストの形で表示させます。そして、

var body: some View {
       NavigationView{
           List{
               FeaturedLandmarks(landmarks: featured)
                   .scaledToFill()
                   .frame(height:200)
                   .clipped()
                   .listRowInsets(EdgeInsets())
               ForEach(categories.keys.sorted(),id: \.self){key in
                   CategoryRow(categoryName: key, items: self.categories[key]!)
               }
               .listRowInsets(EdgeInsets())
                   NavigationLink(destination: LandmarkList()) {
                                      Text("See All")
                   }
               }
               .navigationBarTitle("Featured")
               .navigationBarItems(trailing: profileButton)
               .sheet(isPresented: $showingProfile){
                   Text("User Profile")
               }
       }
   }
ForEach(categories.keys.sorted(),id: \.self){key in
CategoryRow(categoryName: key, items: self.categories[key]!)
}

ですね。ForEachでループさせCategoryRow()でデータを取り出して、表示させています。

あとは見ばえと使いやすいように調整、ボタンをつけ遷移できるようにしています。以下ボタンです。

 var profileButton:some View{
       Button(action: {self.showingProfile.toggle()}){
           Image(systemName: "person.crop.circle")
               .imageScale(.large)
               .accessibility(label: Text("User profile"))
               .padding()
       }
       
   }

で作り、

.navigationBarItems(trailing: profileButton)

で表示します。細かいところはいろいろありますが、大きな流れはこんな感じではないでしょうか。

この記事が気に入ったらサポートをしてみませんか?