Last active
June 21, 2019 22:32
-
-
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
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
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 |
@State
:allthethings:
🎉
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed the horizontal scroll bug and added spacing support, thanks @Mackarous