SwiftUI TabViewでTab動的追加

Tab

ForEachに対応するには、
TabContent

Conforms when Data conforms to RandomAccessCollection, ID conforms to Hashable, and Content conforms to TabContent.
DataがRandomAccessCollectionに準拠し、IDがHashableに準拠し、ContentがTabContentに準拠する場合に適合する。

が必要となります。

TabはTabContentに準拠しています。

extension Tab : TabContent where Value : Hashable, Content : View, Label : View {

Code

import SwiftUI

struct TabInfo: Identifiable {
    var id: Int
    var name : String
}

struct BooksView: View {
    @State private var selectTab: Int = 1
    @State var booksTabInfo: [TabInfo] = [TabInfo(id: 1, name: "Aaaaa"),
                                          TabInfo(id: 2, name: "Bbbbb"),
                                          TabInfo(id: 3, name: "Ccccc")]

    var body: some View {
        TabView(selection: self.$selectTab) {
            ForEach(self.booksTabInfo, content: { boolTabInfo in
                Tab(boolTabInfo.name, systemImage: "calendar", value: boolTabInfo.id) {
                    Text("\(boolTabInfo.name)")
                    Button("add Tab") {
                        let id = self.booksTabInfo.count + 1
                        self.booksTabInfo.append(TabInfo(id: id, name: "tab-\(id)"))
                    }
                }
            })
        }
        .tabViewStyle(.sidebarAdaptable)
    }
}

動作画面

SwiftSwift,SwiftUI

Posted by shi-n