Floating Label TextField for SwiftUI. FloatingLabelTextFieldSwiftUI

Overview

FloatingLabelTextFieldSwiftUI

CI Status Version License Platform

FloatingLabelTextFieldSwiftUI is a small and lightweight SwiftUI framework written in completely swiftUI (not using UIViewRepresentable) that allows to create beautiful and customisable floating label textfield! This library support RTL text (eg. Arabic) and easy to add left view and right view to your text field and customizable.

If you like the project, please do not forget to star ★ this repository and follow me on GitHub.

📦 Requirements

  • iOS 13.0+
  • Xcode 11.2+
  • Swift 5.0

💻 Usage

To start using the component add it to your project using CocoaPods or Swift Package. First of all import FloatingLabelTextFieldSwiftUI

import FloatingLabelTextFieldSwiftUI

struct ContentView: View {
    
    @State private var firstName: String = ""
    
    var body: some View {
        
        FloatingLabelTextField($firstName, placeholder: "First Name", editingChanged: { (isChanged) in
            
        }) {
            
        }.frame(height: 70)
    }
}

FloatingLabelTextFieldStyle and Colors:

You can customize the colors of the textfield by using FloatingLabelTextFieldStyle property or create your own style and set a few properties.

Property

struct ContentView: View {
    
    @State private var firstName: String = ""
    
    var body: some View {
        
        FloatingLabelTextField($firstName, placeholder: "First Name", editingChanged: { (isChanged) in
            
        }) {
            
        }
        .titleColor(.green)
        .selectedLineColor(.blue)
        .selectedTextColor(.blue)
        .selectedTitleColor(.blue)
        .frame(height: 70)
    }
}

FloatingLabelTextFieldStyle

Just two step for create and add style to FloatingLabelTextField.

  1. Create your own theme style. Set property as per your theme.
struct ThemeTextFieldStyle: FloatingLabelTextFieldStyle {
    func body(content: FloatingLabelTextField) -> FloatingLabelTextField {
        content
            .spaceBetweenTitleText(15) // Sets the space between title and text.
            .textAlignment(.leading) // Sets the alignment for text.
            .lineHeight(1) // Sets the line height.
            .selectedLineHeight(1.5) // Sets the selected line height.
            .lineColor(.gray) // Sets the line color.
            .selectedLineColor(.blue) // Sets the selected line color.
            .titleColor(.gray) // Sets the title color.
            .selectedTitleColor(.blue) // Sets the selected title color.
            .titleFont(.system(size: 12)) // Sets the title font.
            .textColor(.black) // Sets the text color.
            .selectedTextColor(.blue) // Sets the selected text color.
            .textFont(.system(size: 15)) // Sets the text font.
            .placeholderColor(.gray) // Sets the placeholder color.
            .placeholderFont(.system(size: 15)) // Sets the placeholder font.
            .errorColor(.red) // Sets the error color.
            .addDisableEditingAction([.paste]) // Disable text field editing action. Like cut, copy, past, all etc.
            .enablePlaceholderOnFocus(true) // Enable the placeholder label when the textfield is focused.
            .allowsHitTesting(true) // Whether this view participates in hit test operations.
            .disabled(false) // Whether users can interact with this.
    }
}
  1. Add style to FloatingLabelTextField.
struct ContentView: View {
    
    @State private var firstName: String = ""
    
    var body: some View {
        FloatingLabelTextField($firstName, placeholder: "First Name", editingChanged: { (isChanged) in
            
        }) {
            
        }
        .floatingStyle(ThemeTextFieldStyle())
        .frame(height: 70)
    }
}

Secure Text Entry

To enable Secure Text Entry use .isSecureTextEntry(true) property.

struct ContentView: View {
    
    @State private var password: String = ""
    
    var body: some View {
        HStack(spacing: 20) {
            FloatingLabelTextField($password, placeholder: "Password", editingChanged: { (isChanged) in
                
            }) {
                
            }
            .isSecureTextEntry(true)
            .frame(height: 70)
        }
    }
}

Left - Right View

Yes, you can easily add your own views, buttons or image to left view or right view of the FloatingLabelTextField.

struct ContentView: View {
    
    @State private var password: String = ""
    @State private var isPasswordShow: Bool = false
    
    var body: some View {
        FloatingLabelTextField($password, placeholder: "Password", editingChanged: { (isChanged) in
            
        }) {
            
        }
        .isSecureTextEntry(!self.isPasswordShow)
            .leftView({ // Add left view.
                Image("password")
            })
            .rightView({ // Add right view.
                Button(action: {
                    withAnimation {
                        self.isPasswordShow.toggle()
                    }
                    
                }) {
                    Image(self.isPasswordShow ? "eye_close" : "eye_show")
                }
            })
            .frame(height: 70)
            .padding()
    }
}

Error Message & Validation

FloatingLableTextFieldSwiftUI supports displaying an error and add text field validations. This can be helpfull for adding validation on your form text field. To enable isShowError property to true and pass text field validations array to text field with message according condition. You can also add validation checker variable to check is text field is valid or not on submit button action.

FloatingLabelTextFieldSwiftUI also have some inbuilt validation regex checker fields like email, password, name, number.. etc.

Here is some example

  1. Email Validation

struct ContentView: View {
    
    @State private var email: String = ""
    @State private var isValidEmail: Bool = false
    
    var body: some View {
        VStack {
            FloatingLabelTextField($email, validtionChecker: $isValidEmail, placeholder: "Email", editingChanged: { (isChanged) in
                
            }) {
                
            }
            .addValidation(.init(condition: email.isValid(.email), errorMessage: "Invalid Email")) /// Sets the validation condition.
                .isShowError(true) /// Sets the is show error message.
                .errorColor(.red) /// Sets the error color.
                .keyboardType(.emailAddress)
                .frame(height: 70)
                .padding()
            
            Button(action: {
                self.endEditing(true)
                
                if self.isValidEmail {
                    print("Valid Email")
                    
                } else {
                    print("Invalid Email")
                }
                
            }) {
                Text("Create")
            }
        }
    }
}
  1. Name Validation

struct ContentView: View {
    
    @State private var lastName: String = ""
    
    var body: some View {
        FloatingLabelTextField($lastName, placeholder: "Last Name", editingChanged: { (isChanged) in
            
        }) {
            
        }
        .isShowError(true) /// Sets the is show error message.
        .addValidations([.init(condition: lastName.isValid(.alphabet), errorMessage: "Invalid Name"),
                         .init(condition: lastName.count >= 2, errorMessage: "Minimum two character long")
        ]) /// Sets the validation conditions.
            .floatingStyle(ThemeTextFieldStyle2())
            .frame(height: 70)
    }
}

🐾 Examples

To run the example project, clone the repo, and run pod install from the Example directory first.

💾 Installation

CocoaPods:

FloatingLabelTextFieldSwiftUI is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'FloatingLabelTextFieldSwiftUI'

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

To integrate FloatingLabelTextFieldSwiftUI into your Xcode project using Xcode 11+, specify it in File > Swift Packages > Add:

https://github.com/kishanraja/FloatingLabelTextFieldSwiftUI.git

Manual

You can download the latest files from our Releases page. After doing so, copy the files in the Sources folder to your project.

🙋🏻‍♂️ Author

kishanraja, [email protected]

💰 Contribution

Feel free to fork the project and send me a pull-request!

📝 Feedback

Please file an Issue.

📜 License

FloatingLabelTextFieldSwiftUI is available under the MIT license. See the LICENSE file for more info.

Comments
  • Issues with validation

    Issues with validation

    Consider the following source code:

    I have discovered a few issue with validation.

    • When a field is required I cannot figure out how to display the error. I am using the below code however the error message just flashes briefly.
       FloatingLabelTextField($username, validtionChecker: $isValidUsername, placeholder: "Username")
          .addValidation(.init(condition: !username.isEmpty, errorMessage: "Username is required"))
          .isShowError(true)
          .errorColor(.red)
          .frame(height: 50)
    
    • Validation does not appear to work on SecureTextEntry fields. In the below example isValidPassword is always false
    FloatingLabelTextField($password, validtionChecker: $isValidPassword, placeholder: "Password")
       .addValidation(.init(condition: !password.isEmpty, errorMessage: "Password is required"))
       .isShowError(true)
       .errorColor(.red)
       .isSecureTextEntry(!self.isPasswordShow)
       .frame(height: 50)
    

    Any assistance would be appreciated

    opened by bludginozzie 3
  • Remove/conditionally import references to UIKit to allow macOS support?

    Remove/conditionally import references to UIKit to allow macOS support?

    I haven't dug into the internals of the code yet, but would it be possible to add support for conditionally importing any references to UIKit? As it stands, the references to UIKit are preventing this library from being used in macOS SwiftUI applications.

    opened by TheGeekPharaoh 2
  • Unable to set Input View

    Unable to set Input View

    how can I set input view with FloatingLabelTextField ? I wanted to display picker instead of keyboard ? but currently can't find a way to set input view. let me know if there is a way.

    opened by sumitchhangani 1
  • Validation issue

    Validation issue

    I was using multiple FloatingLabelTextField on clicked submit button ValidationChecker until validate first text field second text field flag state not change even second text valid.

         FloatingLabelTextField($registrationDetails.firstName,validtionChecker: $isValidFirstname, placeholder: "Voornaam *")
              .addValidations([.init(condition: registrationDetails.firstName.isValid(.name), errorMessage: "Enter Valid Firstname")
              ])
              .isShowError(true)
              .isRequiredField(true, with: "Enter Firstname")
          .floatingStyle(ThemeTextFieldStyle())
          .padding(8)
          .frame(height: 60)
          .background(RoundedRectangle(cornerRadius: 4)
                .fill(Color("textfieldBackgroundColor"))
                        .shadow(color: Color("shadowColor"), radius: 5, x: 0, y: 0))
          .padding()
    
          FloatingLabelTextField($registrationDetails.middleName, placeholder: "Tussenvoegsel ")
              .addValidations([.init(condition: registrationDetails.middleName.isValid(.name), errorMessage: "Enter Valid Middlename")
              ])
              .isShowError(true)
          .floatingStyle(ThemeTextFieldStyle())
          .padding(8)
          .frame(width: 300, height: 60, alignment: .leading)
          .background(RoundedRectangle(cornerRadius: 4)
                .fill(Color("textfieldBackgroundColor"))
                        .shadow(color: Color("shadowColor"), radius: 5, x: 0, y: 0))
          .padding()
    
          FloatingLabelTextField($registrationDetails.lastName,validtionChecker: $isValidLastname, placeholder: "Achternaam *")
              .addValidations([.init(condition: registrationDetails.lastName.isValid(.name), errorMessage: "Enter Valid Lastname")
              ])
              .isShowError(true)
              .isRequiredField(true, with: "Enter Lastname")
          .floatingStyle(ThemeTextFieldStyle())
          .padding(8)
          .frame(height: 60)
          .background(RoundedRectangle(cornerRadius: 4)
                .fill(Color("textfieldBackgroundColor"))
                        .shadow(color: Color("shadowColor"), radius: 5, x: 0, y: 0))
          .padding()
    

    Can you please help.

    opened by vinayakrathod92 1
  • Animate label when focused.

    Animate label when focused.

    Hi, Would be great to have the option to animate the label as soon as the textfield is focused, rather than when the user starts typing.

    Like shown in the material components site: https://material-ui.com/components/text-fields/

    Much Appreciated.

    opened by nirleshem 1
  • Disable editing but enable right/left view buttons

    Disable editing but enable right/left view buttons

    Feature request: Disable editing of the text field, while still enabling buttons added to a left/right view. For example (based on the sample code provided), I can do this:

    var body: some View {
            FloatingLabelTextField($password, placeholder: "Password", editingChanged: { (isChanged) in
                
            }) {
                
            }
            .isSecureTextEntry(!self.isPasswordShow)
                .leftView({ // Add left view.
                    Image("password")
                })
                .rightView({ // Add right view.
                    Button(action: {
                        withAnimation {
                            self.isPasswordShow.toggle()
                        }
                        
                    }) {
                        Image(self.isPasswordShow ? "eye_close" : "eye_show")
                    }
                })
                .frame(height: 70)
                .padding()
        }
    
    

    However, if I want the text field itself to be read-only and i set disabled(true), that also disables the Button in rightView. I'd like to be able to still toggle the visibility of the field while disabling the ability to edit.

    opened by TheGeekPharaoh 1
  • Secure Entry not working on iOS 14.2

    Secure Entry not working on iOS 14.2

    FloatingLabelTextField($passwordText, validtionChecker: $passwordValid, placeholder: "Password") { (bool) in
                
            } commit: {
                
            }
            .isSecureTextEntry(true)
            
            .isShowError(true) /// Sets the is show error message.
                            .errorColor(.red) /// Sets the error color.
            .floatingStyle(MeterTextFieldStyle())
            .frame(height: 51)
    

    That is my code and it does not work properly when run on an iPhone 12 mini. This is the field that shows up: image

    opened by ericagredo 1
  • validtionChecker becomes TRUE only after closing the keyboard

    validtionChecker becomes TRUE only after closing the keyboard

    I defined a FloatingLabelTextField (with var isValidMasterPwd2 as validtionChecker) whose content must be the same as the string inserted in another TextField. If I insert a string identical to the other in this TextField, the variable isValidMasterPwd2 becomes TRUE only after closing the keyboard. Is there a way for the variable to immediately become TRUE as soon as the validity conditions are satisfied?

    FloatingLabelTextField($masterPwd2, validtionChecker: $isValidMasterPwd2, 
    placeholder: "Re-type Password", editingChanged: { (isChanged) in
                    }) {
                    }
                    .isShowError(true)
                    .addValidations([.init(condition: masterPwd1 == masterPwd2, errorMessage: "Password not equal")])
                    .isRequiredField(true, with: "Password field is required")
                    .isSecureTextEntry(!self.isMasterPwd2Show)
                    .modifier(ThemeTextField())
    
    opened by ezamp 1
  • Keyboard type should not allow character and special symbols when type is Numberpad?

    Keyboard type should not allow character and special symbols when type is Numberpad?

    I am creating mobile number field and setting keyboard type as NumberPad. Then following scenario occurs:

    When running with iPad keyboard we are able to enter special characters. (iPad only) We can paste the text which is copied earlier(iPad and iPhone). How to find out each and every character typed? callbacks not calling

    I am able to do this without your library by reading this tutorial https://programmingwithswift.com/numbers-only-textfield-with-swiftui/

    see image here:

    Screen Shot 2020-10-17 at 12 48 44 PM

    I don"t have clear idea where to implement this in your class files. It would much better with those features.

    Hope you got my points, Thanks for your great work.

    opened by karthisiva 1
  • Feature/multiline text

    Feature/multiline text

    Wanted to have multiline text. In order to do that, had to use iOS 16 available init with axis parameter. It also changes how focus is managed, by forcing to use @FocusState - which is available from iOS 15 and up, as a property wrapper. Since it is needed for a stored property, can't use @available annotation on it. So had to bump min iOS version for the lib to iOS 15.

    Also had to deal with maxHeight: infinity breaking the layout - wanted to have multiline field expand as more lines are used; instead of a big field from the start.

    Let me know if you are willing to accept the change; or have any other ideas to keep it iOS 13 compatible.

    opened by michallaskowski 0
  • Fixed

    Fixed "Modifying state during view update, this will cause undefined …

    When editing, XCode throws a warning saying:

    Modifying state during view update, this will cause undefined behavior

    To read more about it check: https://www.hackingwithswift.com/quick-start/swiftui/how-to-fix-modifying-state-during-view-update-this-will-cause-undefined-behavior

    opened by afern247 0
  • UI Test Case for FloatingLabelTextField

    UI Test Case for FloatingLabelTextField

    How can i give accessibilityIdentifier to text field, because if i add accessibilityIdentifier to FloatingLabelTextField it did not work with UI Test Case

    Example:

    FloatingLabelTextField($firstName, placeholder: "First Name", editingChanged: { (isChanged) in 
    })
    accessibilityIdentifier("firstname_textfield")
    

    Than i code in Test Case

    let firstnameTextField = app.textFields["firstname_textfield"]
            firstnameTextField.tap()
            firstnameTextField.typeText("test user")
    

    in text field it is not typing "test user" can you please let me know how to make working in UI Test Case?

    help wanted 
    opened by kaushik-orangeapp 0
  • Geometry Behavior

    Geometry Behavior

    Thanks for the great package. Unfortunately due to your use of .frame(... maxHeight: .infinity ...), the view tries to grab the maximum of space, which means e.g., in a VBox, it overrides your any Spacers, etc. and aligns itself always to the bottom.

    I think it would be more versatile without these settings.

    opened by mickeyl 0
  • validtion Checker

    validtion Checker

    hi, the validtion Checker variable is being changed to false when not passing the validation but not becoming true when it passes it the error label is not showing but the binding variable still false please advise regards

    opened by seniorAyman 0
Releases(5.0.0)
Owner
Kishan Raja
iOS Developer
Kishan Raja
Floating-textfield-swiftui - Floating textfield With SwiftUI

floating_textfield-swiftui Hey, Guys welcome to this tutorial. In this complete

null 1 Feb 11, 2022
A floating label style for SwiftUI's TextField.

FloatingLabelTextFieldStyle A floating label style for TextField with support for displaying error messages. Requirements iOS 15.0+ macOS 12.0+ Instal

Red Davis 13 Aug 22, 2022
DTTextField is a custom textfield with floating placeholder and error label

DTTextField Introduction DTTextField is a UITextField library with floating placeholder and error label. Floating placeholder inspired from JVFloatLab

Dhaval Thanki 310 Jan 5, 2023
This is the demo repository for having floating TextField in swift UI

ed-floating-field-swiftui This is the demo repository for having floating TextField in swift UI The inputs fields should not be empty Validations for

Patrick 1 May 26, 2022
A SwiftUI TextField with a prompt (or placeholder) that floats above the text field when active or not empty. Requires iOS 15.

FloatingPromptTextField A prompt is the label in a text field that informs the user about the kind of content the text field expects. In a default Tex

Emilio Peláez 43 Nov 3, 2022
Elegant SwiftUI phone number textField.

iPhoneNumberField ☎️ Format phone numbers as they're typed—entirely in SwiftUI. ?? Get Started | Examples | Customize | Features | Install | And it's

Seyed Mojtaba Hosseini Zeidabadi 358 Dec 30, 2022
An optional TextField Replacement for SwiftUI

TextInputView A TextField Replacement In his excellent YouTube tutorial series on Building SwiftUI Components, Peter Friese (@peterfriese on Twitter)

Stewart Lynch 6 Aug 9, 2022
A custom TextField with a switchable icon which shows or hides the password and enforce good password policies

PasswordTextField A custom TextField with a switchable icon which shows or hides the password and enforces good password policies, written in Swift. ⭐

Chris Jimenez 304 Dec 29, 2022
Simple placeholder move textfield

PlaceholderTextField Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 11.0 o

null 6 Mar 9, 2022
TextField with DropDown support using UIPickerView

IQDropDownTextField TextField with DropDown support using UIPickerView Installing Install using cocoapods. Add in your Podfile: pod 'IQDropDownTextFie

Mohd Iftekhar Qurashi 301 Jun 29, 2022
TextField with smart suggestion

AutoCompleteTextField Features Provides a subclass of UITextField that has suggestion from input Has autocomplete input feature Data suggestion are pr

Neil Francis Ramirez Hipona 63 Nov 13, 2022
Library that allows you binding `enabled` property of button with textable elements (TextView, TextField)

What is NxEnabled? It's a fairly common case, when the enabled state of button depends on some textable elements such as TextView, TextField. So this

Nikita Ermolenko 33 Sep 20, 2021
Awesome TextField is a nice and simple libriary for iOS and Mac OSX

Awesome TextField is a nice and simple libriary for iOS and Mac OSX. It's highly customisable and easy-to-use tool. Works perfectly for any registration or login forms in your app.

Alexander Shoshiashvili 225 Nov 21, 2022
Apple TextField created according to the Material.IO guidelines of 2019. Featured at Medium.

CocoaTextField Highly customizable text field created according to Material.IO guidelines. Minimum iOS version 11.0 Carthage github "edgar-zigis/Cocoa

Edgar Žigis 266 Nov 26, 2022
TTextField is developed to help developers can initiate a fully standard textfield including title, placeholder and error message in fast and convinient way without having to write many lines of codes

TTextField is developed to help developers can initiate a fully standard textfield including title, placeholder and error message in fast and convinient way without having to write many lines of codes

Nguyen Duc Thinh 7 Aug 28, 2022
A beautiful and flexible text field control implementation of "Float Label Pattern". Written in Swift.

SkyFloatingLabelTextField SkyFloatingLabelTextField is a beautiful, flexible and customizable implementation of the space saving "Float Label Pattern"

Skyscanner 4k Jan 1, 2023
Changes the color of the label text when the button is pressed and also prints hello to the console

MY FIRST APP App Description This app changes the color of the label text when the button is pressed and also prints "hello" to the console. App Walk-

null 0 Nov 29, 2021
UITextField subclass with floating labels

JVFloatLabeledTextField JVFloatLabeledTextField is the first implementation of a UX pattern that has come to be known the "Float Label Pattern". Due t

Jared Verdi 7.2k Jan 2, 2023
UITextField and UITextView subclasses with placeholders that change into floating labels when the fields are populated with text.

Deprecated Please use JVFloatLabeledTextField instead or feel free to chime in on an issue if you'd like to take over the repo. RPFloatingPlaceholders

rob phillips 1.1k Jan 5, 2023