Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Last active Aug 15, 2020
Embed
What would you like to do?
So far it outputs the frames of the cells, but I am stuck trying to hide the ones that are outside of the widget
import SwiftUI
struct RegularEventCell: View {
let color: Color
let title: String
let description: String?
var body: some View {
HStack {
color.frame(width: 3)
VStack (alignment: .leading, spacing: 0) {
Text(title)
.font(.caption)
if let desc = description
{
Text(desc)
.font(.caption2)
.foregroundColor(.secondary)
}
}
Spacer()
}
.padding([.leading, .trailing], 10)
.padding([.bottom, .top], 5)
}
}
extension View {
func readFrame(onChange: @escaping (CGRect) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
Color.clear.onAppear() {
print(geometryProxy.frame(in: .global))
}
.preference(key: FramePreferenceKey.self, value: geometryProxy.frame(in: .global))
}
)
.onPreferenceChange(FramePreferenceKey.self, perform: onChange)
}
}
private struct FramePreferenceKey: PreferenceKey {
static var defaultValue: CGRect = .zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {}
}
struct ModelRow: Identifiable {
let id: String = NSUUID().uuidString
let title: String
let description: String?
}
let rows = [ModelRow(title: "One", description: "First"),
ModelRow(title: "Two", description: nil),
ModelRow(title: "Three", description: "Third"),
ModelRow(title: "Four", description: nil),
ModelRow(title: "Five", description: "Fifth"),
ModelRow(title: "Six", description: nil)]
struct ContentView : View {
@State var hiddenCells = Set<String>()
var body: some View {
let content = GeometryReader { geometry in // causes VStack to be same size as widget
VStack(alignment: .leading, spacing: 1) {
ForEach(rows) { row in
Group {
RegularEventCell(color: .red, title: row.title, description: row.description).readFrame { frame in
if frame.maxY > geometry.size.height
{
hiddenCells.insert(row.id)
}
}
Divider()
}
.opacity(hiddenCells.contains(row.id) ? 0.3 : 1)
}
Spacer()
}
}
return content
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().previewLayout(.fixed(width: 200, height: 170))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment