64 lines
1.7 KiB
Swift
64 lines
1.7 KiB
Swift
//
|
|
// ForEach.swift
|
|
// MacBackend
|
|
//
|
|
// Created by david-swift on 31.12.2024.
|
|
//
|
|
|
|
import SwiftUI
|
|
|
|
/// Align a dynamic number of items horizontally or vertically.
|
|
public struct ForEach<Item>: SwiftUIWidget where Item: Identifiable {
|
|
|
|
/// The data.
|
|
var data: [Item]
|
|
/// The content.
|
|
var content: (Item) -> Body
|
|
/// Whether the items are aligned horizontally.
|
|
var horizontal: Bool
|
|
|
|
/// The wrapped views.
|
|
public var wrappedViews: [String: Meta.AnyView] {
|
|
data.reduce([:]) { partialResult, item in
|
|
var partialResult = partialResult
|
|
partialResult[item.id.hashValue.description] = content(item)
|
|
return partialResult
|
|
}
|
|
}
|
|
|
|
/// Initialize a ``ForEach`` view.
|
|
/// - Parameters:
|
|
/// - data: The data.
|
|
/// - horizontal: Whether the items are aligned horizontally.
|
|
/// - content: The content for each data item.
|
|
public init(
|
|
_ data: [Item],
|
|
horizontal: Bool = false,
|
|
@Meta.ViewBuilder content: @escaping (Item) -> Body
|
|
) {
|
|
self.data = data
|
|
self.content = content
|
|
self.horizontal = horizontal
|
|
}
|
|
|
|
/// Get the SwiftUI view.
|
|
/// - Parameter properties: The widget data.
|
|
/// - Returns: The SwiftUI view.
|
|
@SwiftUI.ViewBuilder
|
|
public static func view(properties: Self) -> some SwiftUI.View {
|
|
let forEach = SwiftUI.ForEach(properties.data) { item in
|
|
MacBackendView(item.id.hashValue.description)
|
|
}
|
|
if properties.horizontal {
|
|
SwiftUI.HStack {
|
|
forEach
|
|
}
|
|
} else {
|
|
SwiftUI.VStack {
|
|
forEach
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|