Skip to content

Instantly share code, notes, and snippets.

@mevanloon
Created May 7, 2022 16:33
Show Gist options
  • Save mevanloon/8c903960a652b9383ddd6b8558381cc6 to your computer and use it in GitHub Desktop.
Save mevanloon/8c903960a652b9383ddd6b8558381cc6 to your computer and use it in GitHub Desktop.
wrap my bitch up
import SwiftUI
import PlaygroundSupport
struct BadgesHeightPreferenceKey: PreferenceKey {
static var defaultValue: Int = 0
static func reduce(value: inout Int, nextValue: () -> Int) {
value = nextValue()
}
}
struct BadgesView: View {
let badges: [String]
var body: some View {
var width = 0.0
var height = 0.0
return GeometryReader { geo in
ZStack(alignment: .topTrailing) {
ForEach(badges.indices, id: \.self) { i in
Text("\(i) \(badges[i])")
.lineLimit(0)
.padding(4)
.background(.pink)
.foregroundColor(.white)
.cornerRadius(6)
.padding(4)
.opacity(0.5)
.alignmentGuide(.trailing, computeValue: { dim in
var res = width
if (dim.width + width > geo.size.width) {
height += dim.height
width = dim.width
return dim[.trailing]
}
width += dim.width
return dim[.trailing] + res
})
.alignmentGuide(.top, computeValue: { dim in
var res = height
// If the last, reset, because vars might keep
if i == badges.indices.last! {
height = 0
width = 0
}
return -res
})
}
}
}
}
}
struct CoolView: View {
@State private var someList = [
"Hey I'm string",
"I too",
"I'm a long-ass string what's up ya doofus",
"Another one",
"I too",
"I'm a long-ass string what's up ya doofus",
"I'm a long-ass string what's up ya doofus",
"Another one",
"I too",
"Hey I'm string",
"I too",
"Hey I'm string",
"I too",
"Hey I'm string",
"I too",
"I'm a long-ass string what's up ya doofus",
"I too",
]
var body: some View {
VStack(alignment: .leading) {
BadgesView(badges: someList)
}
.frame(maxWidth: 600, minHeight: 100, maxHeight: 400)
.font(.title)
.background(.orange.opacity(0.2))
}
}
PlaygroundPage.current.setLiveView(CoolView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment