Skip to content

Instantly share code, notes, and snippets.

@Jimmy-Prime
Created November 2, 2020 09:40
Show Gist options
  • Save Jimmy-Prime/be7ae90812377402439f718d58933e0e to your computer and use it in GitHub Desktop.
Save Jimmy-Prime/be7ae90812377402439f718d58933e0e to your computer and use it in GitHub Desktop.
SwiftUI floating label textfield
// Because Label's size don't match, transition looks weird.
import SwiftUI
struct FloatingLabelTextField: View {
@Namespace private var namespace
let placeholder: String
@Binding var text: String
@State private var isTextFieldFirstResponder: Bool = false
var showLabel: Bool {
isTextFieldFirstResponder || !text.isEmpty
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ZStack {
Text(placeholder)
.foregroundColor(Color(.systemBackground))
if showLabel {
Text(placeholder)
.matchedGeometryEffect(id: "label", in: namespace)
.foregroundColor(.secondary)
}
}
.font(.footnote)
ZStack(alignment: .leading) {
if !showLabel {
Text(placeholder)
.matchedGeometryEffect(id: "label", in: namespace)
.foregroundColor(.secondary)
}
TextField("", text: $text, onEditingChanged: { isFirstResponder in
withAnimation {
isTextFieldFirstResponder = isFirstResponder
}
})
}
.font(.body)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment