Created
July 20, 2020 21:42
-
-
Save CodeSlicing/4b03febc950d483406f3cae4ee01d399 to your computer and use it in GitHub Desktop.
View showing the problem that occurs when using GeometryReader with a non-greedy view. A companion file to CodeSlicing: CoreConcepts in SwiftUI - GeometryReader
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 | |
import PureSwiftUI | |
private let size: CGFloat = 200 | |
private let gradient = LinearGradient([Color.red, Color.yellow], to: .bottomTrailing) | |
struct GeometryReaderProblemDemo: View { | |
@State private var text = "Hello" | |
@State private var textSize: CGSize = .zero | |
@State private var appendingText = "" | |
var body: some View { | |
VStack { | |
UnderlinedText(text + " " + appendingText, font: .title) | |
TextField("Append something...", text: $appendingText) | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
.autocapitalization(.none) | |
.padding(25) | |
} | |
.greedyFrame() | |
.background(gradient) | |
.edgesIgnoringSafeArea(.all) | |
} | |
} | |
private struct UnderlinedText: View { | |
private let text: String | |
private let font: Font | |
private let padding: CGFloat | |
@State private var textSize: CGSize = .zero | |
init(_ text: String, font: Font = .title, padding: CGFloat = 25) { | |
self.text = text | |
self.font = font | |
self.padding = padding * 2 | |
} | |
var body: some View { | |
ZStack { | |
Text(self.text) | |
.font(self.font) | |
.fixedSize() | |
.geometry(id: text) { (geo: GeometryProxy) in | |
self.textSize = geo.size | |
} | |
Color.black | |
.frame(textSize.width, 2) | |
.yOffset(textSize.height / 2) | |
} | |
.frame(textSize.width + padding, textSize.height + padding) | |
.background(Color.white.cornerRadius(10).shadow(5)) | |
.blendMode(.darken) | |
} | |
} | |
public extension View { | |
func geometry(_ geoCallback: @escaping (GeometryProxy) -> ()) -> some View { | |
geometry(id: 1, geoCallback) | |
} | |
func geometry<T: Hashable>(id: T, _ geoCallback: @escaping (GeometryProxy) -> ()) -> some View { | |
background(GeometryReader { (geo: GeometryProxy) in | |
Color.clear.onAppear { | |
geoCallback(geo) | |
} | |
.id(id) | |
}) | |
} | |
} | |
struct GeometryReaderProblemDemo_Previews: PreviewProvider { | |
struct GeometryReaderProblemDemo_Harness: View { | |
var body: some View { | |
GeometryReaderProblemDemo() | |
} | |
} | |
static var previews: some View { | |
GeometryReaderProblemDemo_Harness() | |
.previewDevice(.iPhone_11_Pro_Max) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment