Skip to content

Instantly share code, notes, and snippets.

View GeorgeElsham's full-sized avatar
🔨
🏖️📦

George Elsham GeorgeElsham

🔨
🏖️📦
View GitHub Profile
@GeorgeElsham
GeorgeElsham / ReadSize.swift
Created April 28, 2024 18:20
Read view size
import SwiftUI
extension View {
func readSize(_ reader: @escaping (CGSize) -> Void) -> some View {
background {
GeometryReader { geo in
Color.clear.preference(key: SizeKey.self, value: geo.size)
}
.onPreferenceChange(SizeKey.self) { size in
reader(size)
struct ContentView: View {
@State private var height: CGFloat = 0
var body: some View {
HStack {
CustomButton("Directions", imageName: "arrow.triangle.turn.up.right.circle.fill") {
//
}
.buttonStyle(.borderedProminent)
@GeorgeElsham
GeorgeElsham / GeometryReaderPreferenceKeyExample.swift
Last active March 3, 2023 16:02
This is an example of using PreferenceKey with GeometryReader. Whenever this scaled red square changes geometry because of the space given by the parent view, the preference will update, updating the State variable. This will not causes State changes during view update issues.
struct ContentView: View {
@State private var size: CGFloat = 0
var body: some View {
Color.red
.scaledToFit()
.background(
GeometryReader { geo in
Color.clear.preference(
key: SizePreferenceKey.self,
@GeorgeElsham
GeorgeElsham / GeometryReaderModifier.swift
Last active January 28, 2024 13:51
Get geometry of view without breaking the layout
/*
MIT License
Copyright (c) [2023] [George Elsham]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
@GeorgeElsham
GeorgeElsham / Text+readStrings.swift
Last active May 11, 2021 20:00
Gets underlying string from SwiftUI's `Text`. Why would you want this? Who knows...
import SwiftUI
extension Text {
func readStrings() -> [String] {
let mirror = Mirror(reflecting: self)
if let keyMirror = mirror.descendant("storage", "anyTextStorage", "key") {
// Only contains one string
let newMirror = Mirror(reflecting: keyMirror)