Last active
September 24, 2024 13:29
-
-
Save SagarAjudiya/5e5fcb4b0fa0f16cb2c6fddf7a0d1733 to your computer and use it in GitHub Desktop.
Floating placeholder TextField in SwiftUI.
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
struct FloatingTextField: View { | |
// MARK: - Variable | |
private let textFieldHeight: CGFloat = 50 | |
private let placeHolderText: String | |
@Binding private var text: String | |
@State private var isEditing = false | |
let leftIcon: String? | |
let rightIcon: String? | |
private var shouldPlaceHolderMove: Bool { | |
isEditing || (text.count != 0) | |
} | |
// MARK: - init | |
public init(placeHolder: String, | |
text: Binding<String>, leftIcon: String? = nil, rightIcon: String? = nil) { | |
self._text = text | |
self.placeHolderText = placeHolder | |
self.leftIcon = leftIcon | |
self.rightIcon = rightIcon | |
} | |
var body: some View { | |
ZStack(alignment: .leading) { | |
HStack { | |
// Left View | |
if leftIcon != nil { | |
Button { | |
} label: { | |
Image(systemName: leftIcon ?? "person") | |
.resizable() | |
.frame(width: 18, height: 18) | |
.aspectRatio(contentMode: .fit) | |
.tint(.black) | |
} | |
} | |
// Text Fied | |
TextField(isEditing ? "" : placeHolderText, text: $text, onEditingChanged: { (edit) in | |
isEditing = edit | |
}) | |
.foregroundColor(Color.primary) | |
.accentColor(Color.red) // cursor color | |
.animation(Animation.easeInOut(duration: 0.4), value: EdgeInsets()) | |
.frame(alignment: .leading) | |
// Right Icon | |
if rightIcon != nil { | |
Button { | |
} label: { | |
HStack { | |
Text("Verify") | |
.font(.caption) | |
.hidden() | |
Image(systemName: rightIcon ?? "person") | |
.resizable() | |
.frame(width: 18, height: 18) | |
.aspectRatio(contentMode: .fit) | |
.tint(.black) | |
} | |
} | |
} | |
} | |
.padding() | |
.background(Color(isEditing ? .white : .systemGray4)) | |
.clipShape(RoundedRectangle(cornerRadius: 8)) | |
.overlay { | |
RoundedRectangle(cornerRadius: 8) | |
.stroke(lineWidth: isEditing ? 1: 0) | |
} | |
// Floating Placeholder | |
Text(isEditing ? " " + placeHolderText + " " : "") | |
.foregroundColor(Color.secondary) | |
.scaleEffect(shouldPlaceHolderMove ? 1.0 : 1.2) | |
.animation(Animation.easeInOut(duration: 0.4), value: shouldPlaceHolderMove) | |
.background(Color(UIColor.systemBackground)) | |
.padding(shouldPlaceHolderMove ? | |
EdgeInsets(top: 0, leading: 15, bottom: textFieldHeight, trailing: 0) : | |
EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 0)) | |
} | |
.frame(height: textFieldHeight) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment