Created
August 13, 2020 19:13
-
-
Save mattyoung/848d94624a37e042297aa280586d7f4e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| // this demonstrate preference/onPreferenceChange propagate size value | |
| // to set View size do not work. The value is propagated out as can be | |
| // verified by seeing the print() output from closure of .onPreferenceChange() | |
| // but size value is not reflected inside makeBody() | |
| struct CircleProgressViewStyle: ProgressViewStyle, PreferenceKey { | |
| static var defaultValue: CGFloat = 0 | |
| static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { | |
| value = nextValue() | |
| } | |
| // this is value is set with onPreferenceChange() | |
| @State var size: CGFloat? | |
| func makeBody(configuration: Configuration) -> some View { | |
| GeometryReader { proxy in | |
| ZStack { | |
| Circle() | |
| .stroke(Color.orange, lineWidth: 5) | |
| Text("size: \(size ?? CGFloat.nan)") | |
| } | |
| .preference(key: Self.self, value: min(proxy.size.width, proxy.size.height)) | |
| } | |
| // the closure here is called, but size is not reflected inside makeBody | |
| .onPreferenceChange(Self.self) { print("size is \($0)"); size = $0 } | |
| // setting frame size here has no effect, why? | |
| .frame(width: size, height: size) | |
| .border(Color.red) | |
| } | |
| } | |
| struct CircleProgressViewStyleDemo: View { | |
| var body: some View { | |
| ProgressView(value: 0.5) | |
| .progressViewStyle(CircleProgressViewStyle()) | |
| .border(Color.yellow) | |
| .padding() | |
| } | |
| } | |
| struct CircleProgressViewStyleDemo_Previews: PreviewProvider { | |
| static var previews: some View { | |
| CircleProgressViewStyleDemo() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment