Created
November 2, 2020 09:40
-
-
Save Jimmy-Prime/be7ae90812377402439f718d58933e0e to your computer and use it in GitHub Desktop.
SwiftUI floating label textfield
This file contains 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
// 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