Created
October 12, 2020 07:22
-
-
Save kuroyam/eea61a8bb555bc5bfc1b043a41dcab1c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@available(iOS 13.0, OSX 10.15, *) | |
struct Grid<Data, Content>: View where Data: RandomAccessCollection, Content: View, Data.Index == Int, Data.Element: Identifiable { | |
private let data: [GridData<Data>] | |
private let column: Int | |
private let content: (Data.Index, Data.Element) -> Content | |
init(_ data: Data, column: Int = 2, content: @escaping (Data.Index, Data.Element) -> Content) { | |
self.column = column | |
self.content = content | |
// 最適なやりかたではないかも | |
self.data = data | |
.reduce(into: [], { result, element in | |
guard let last = result.last else { | |
result.append([element]) | |
return | |
} | |
if last.count == column { | |
result.append([element]) | |
} else { | |
result.removeLast() | |
result.append(last + [element]) | |
} | |
}) | |
.enumerated() | |
.map { index, column in | |
GridData(id: index, data: column) | |
} | |
} | |
public var body: some View { | |
List(zip(data.indices, data).map { $0 }, id: \.1.id) { listIndex, gridData in | |
HStack { | |
ForEach(gridData.data.indices) { columnIndex in | |
content(listIndex * column + columnIndex, gridData.data[columnIndex]) | |
} | |
} | |
} | |
} | |
} | |
struct GridData<Data>: Identifiable where Data: RandomAccessCollection, Data.Element: Identifiable { | |
let id: Int | |
let data: [Data.Element] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment