Last active
February 21, 2024 18:31
-
-
Save ryanlintott/00e2063f13d751be1f2647e31639d50f to your computer and use it in GitHub Desktop.
An example of a label that grows and shrinks in overall size and frame height. Requires FrameUp https://github.com/ryanlintott/FrameUp
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
// | |
// ShrinkingLabel.swift | |
// FrameUpExample | |
// | |
// Created by Ryan Lintott on 2024-02-21. | |
// | |
import FrameUp | |
import SwiftUI | |
struct ShrinkingLabel: View { | |
@Binding var isFocused: Bool | |
@State private var textSize: CGSize? = nil | |
let text: Text | |
var scale: CGFloat { | |
isFocused ? 1 : 0.6 | |
} | |
var adjustedHeight: CGFloat? { | |
guard let textSize else { return nil } | |
return textSize.height * scale | |
} | |
var body: some View { | |
text | |
.frame(maxWidth: .infinity, alignment: .leading) | |
.fixedSize(horizontal: false, vertical: true) | |
.onSizeChange { newValue in | |
textSize = newValue | |
} | |
.scaleEffect(scale, anchor: .topLeading) | |
.frame(maxHeight: adjustedHeight, alignment: .top) | |
} | |
} | |
struct ShrinkingLabelExample: View { | |
@State private var isFocused = false | |
var body: some View { | |
VStack(alignment: .leading, spacing: 10) { | |
Text("Example with scaleEffect that will not adjust the frame.") | |
Text("Here is a label with some long text that will span two lines.") | |
.scaleEffect(isFocused ? 1 : 0.7, anchor: .bottomLeading) | |
Text("Example with FrameUp that will adjust the frame.") | |
ShrinkingLabel(isFocused: $isFocused, text: Text("Here is a label with some long text that will span two lines.")) | |
Toggle("isFocused", isOn: $isFocused) | |
} | |
.animation(.easeInOut, value: isFocused) | |
.padding() | |
.frame(maxHeight: .infinity, alignment: .top) | |
} | |
} | |
#Preview { | |
ShrinkingLabelExample() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment