konohazukux / swiftSample

0 stars 0 forks source link

タブバーを作る #11

Closed konohazukux closed 4 months ago

konohazukux commented 4 months ago

SwiftUIでタブバーを追加するには、TabViewを使用します。以下は、既存のコードにタブバーを追加する例です。

既存のコードにタブバーを追加

import SwiftUI

@main
struct MyListAppApp: App {
    var body: some Scene {
        WindowGroup {
            MainView()
        }
    }
}

struct MainView: View {
    var body: some View {
        TabView {
            ContentView()
                .tabItem {
                    Label("To-Do List", systemImage: "list.bullet")
                }
            SettingsView()
                .tabItem {
                    Label("Settings", systemImage: "gear")
                }
        }
    }
}

struct ContentView: View {
    @StateObject private var viewModel = ToDoViewModel()

    var body: some View {
        NavigationView {
            List {
                ForEach($viewModel.toDoItems) { $item in
                    HStack {
                        Text(item.title)
                        Spacer()
                        Image(systemName: item.isCompleted ? "checkmark.circle.fill" : "circle")
                            .foregroundColor(item.isCompleted ? .green : .gray)
                            .onTapGesture {
                                item.toggleCompletion()
                            }
                    }
                }
            }
            .navigationTitle("To-Do List")
        }
    }
}

struct SettingsView: View {
    var body: some View {
        Text("Settings")
            .font(.largeTitle)
            .padding()
    }
}

struct ToDoItem: Identifiable {
    let id = UUID()
    let title: String
    var isCompleted: Bool

    mutating func toggleCompletion() {
        isCompleted.toggle()
    }
}

class ToDoViewModel: ObservableObject {
    @Published var toDoItems = [
        ToDoItem(title: "Buy groceries", isCompleted: false),
        ToDoItem(title: "Walk the dog", isCompleted: true),
        ToDoItem(title: "Read a book", isCompleted: false)
    ]

    func toggleCompletion(of item: ToDoItem) {
        if let index = toDoItems.firstIndex(where: { $0.id == item.id }) {
            toDoItems[index].toggleCompletion()
        }
    }
}

説明

この構造により、アプリにタブバーが追加され、異なる画面間を簡単に切り替えられるようになります。

konohazukux commented 4 months ago

200dc929ff818c30185e92b0ab64cbac46aa3a09