Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- struct TimestampedRect: Equatable {
- var date: Date
- var rect: CGRect
- }
- struct MyTextPreferenceKey: PreferenceKey {
- typealias Value = TimestampedRect
- static var defaultValue: TimestampedRect = TimestampedRect(date: Date(), rect: .zero)
- static func reduce(value: inout TimestampedRect, nextValue: () -> TimestampedRect) {
- let next = nextValue()
- if (next.date > value.date) {
- value = next
- }
- }
- }
- struct ContentView : View {
- @State private var rect: CGRect = .zero
- var body: some View {
- ZStack(alignment: .topLeading) {
- RoundedRectangle(cornerRadius: 15)
- .stroke(lineWidth: 3.0)
- .foregroundColor(Color.green)
- .frame(width: rect.width, height: rect.height)
- .offset(x: rect.minX, y: rect.minY)
- .animation(.easeInOut(duration: 0.5))
- VStack {
- Spacer()
- HStack {
- MonthView("January")
- MonthView("February")
- MonthView("March")
- MonthView("April")
- }
- Spacer()
- HStack {
- MonthView("May")
- MonthView("June")
- MonthView("July")
- MonthView("August")
- }
- Spacer()
- HStack {
- MonthView("September")
- MonthView("October")
- MonthView("November")
- MonthView("December")
- }
- Spacer()
- }
- .onPreferenceChange(MyTextPreferenceKey.self) { preference in
- rect = preference.rect
- }
- }
- .coordinateSpace(name: "main")
- }
- }
- struct MonthView: View {
- @State var date: Date = .distantPast
- let label: String
- init(_ label: String) {
- self.label = label
- }
- var body: some View {
- let preferenceView = MyPreferenceViewSetter(date: date)
- Text(label)
- .padding(10)
- .background(preferenceView)
- .onTapGesture {
- date = Date()
- }
- }
- }
- struct MyPreferenceViewSetter: View {
- let date: Date
- var body: some View {
- GeometryReader { geometry in
- Color.clear
- .preference(key: MyTextPreferenceKey.self,
- value: TimestampedRect(date: date, rect: geometry.frame(in: .named("main"))))
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement