Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active June 21, 2019 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/a783c2318f17700e52dc5ef54e6b86a2 to your computer and use it in GitHub Desktop.
Save IanKeen/a783c2318f17700e52dc5ef54e6b86a2 to your computer and use it in GitHub Desktop.
Playing with Swift UI to see if it's possible to build a 'CollectionView' type thing
import SwiftUI
extension Array {
func chunk(size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
return Array(self[$0..<Swift.min($0 + size, count)])
}
}
}
extension Array: Identifiable where Element: Identifiable {
public var id: String {
return map({ "\($0.id)" }).joined(separator: ":")
}
}
struct ContentView: View {
@State var width = 3
@State var spacing: CGFloat = 5
@State var items: [Int] = Array(1...100)
var body: some View {
GeometryReader { proxy in
ScrollView {
VStack(alignment: .leading) {
ForEach(self.items.chunk(size: self.width)) { row in
HStack(alignment: .center, spacing: self.spacing) {
ForEach(row) { item in
Text("\(item)")
.frame(
width: proxy.frame(in: .local).width / CGFloat(self.width) - self.spacing,
height: proxy.frame(in: .local).width / CGFloat(self.width) - self.spacing
)
.background(Color.red)
}
}
}
}
.background(Color.blue)
.offset(x: self.spacing / 2, y: 0)
}
}
}
}
import PlaygroundSupport
let view = UIHostingController(rootView: ContentView())
PlaygroundPage.current.liveView = view
@IanKeen
Copy link
Author

IanKeen commented Jun 21, 2019

Fixed the horizontal scroll bug and added spacing support, thanks @Mackarous

@IanKeen
Copy link
Author

IanKeen commented Jun 21, 2019

@State :allthethings:

@Mackarous
Copy link

🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment