Focus text field in SwiftUI dynamically and progress through form using iOS keyboard.

Overview

Focuser

Focuser allows to focus SwiftUI text fields dynamically and implements ability move go through the form using Keyboard for iOS 13 and iOS 14. Implementation is modeled to follow Apple @FocusState property wrapper however instead of however instead of @FocusState we use @FocusStateLegacy and for .focused(...) we use .focusedLegacy(...). Since most of us cannot update our apps to serve iOS 15 exclusively Focuser will provide an easy way to change first responder and connect to keyboard "next"/"done" buttons.

Preview

Preview gif of Focuser

Install

We are going to maintain Focuser and extend its functionality in the near future. You can use Focuser in your project using SPM

File > Swift Packages > Add Package Dependency and use

[email protected]:art-technologies/swift-focuser.git

Example

Feel free to download full Xcode example project in Example folder.

To use Focuser you first need to import Focuser and define an enum corresponding to text fields.

import Focuser

enum FormFields {
    case username, password, name
}

Since Focuser allows to focus keyboard to the next text fields using keybaord we have to provide additional information of what the next field should be. We provide this using extension on our struct comforming to FocusStateCompliant protocol. In addition of providing computed variable next we also provide last. This indicates to Focuser when it should show "done" keyboard button instead of "next". To resign first responder (hide keyboard) set your focusedField to nil.

extension FormFields: FocusStateCompliant {

    static var last: FormFields {
        .name
    }

    var next: FormFields? {
        switch self {
        case .username:
            return .password
        case .password:
            return .name
        default: return nil
        }
    }
}

Finally we can build our form

struct ContentView: View {
    @FocusStateLegacy var focusedField: FormFields?
    @State var username = ""
    @State var password = ""
    @State var name = ""

    var body: some View {
        VStack{
            TextField("Username", text: $username)
                .focusedLegacy($focusedField, equals: .username)

            TextField("Password", text: $password)
                .focusedLegacy($focusedField, equals: .password)

            TextField("Name", text: $name)
                .focusedLegacy($focusedField, equals: .name)

            Button(action: {
                focusedField = FormFields.password
            }) {
                Text("Focus Password")
            }
        }
        .padding()
    }
}

Here we introduced "Focus Password" button showing how to focus a specific text field dynamically.

Caveats

Make sure to apply .focusedLegacy modifier as the last modifier to TextField. I will make a fix later on to aleviate the order issue.

TextField("Username", text: $username)
   .padding(9)
   .background(Color(.systemGray6))
   .cornerRadius(8)
   .focusedLegacy($focusedField, equals: .username)

Comparison to iOS 15 @FocusState

The API is analogous and our property wrapper has exactly the same definition. If you ever decide to switch to iOS 15 wrapper, all you need to do is replace

@FocusStateLegacy -> @FocusState

.focusedLegacy(...) -> .focused(...)

However, Focuser additionally offers to show different keyboard return button such as "next" or "done" based on where you are in the form.

To do

  • Support for TextEditor
Comments
  • Does this work with SecureField as well?

    Does this work with SecureField as well?

    Sorry but I'm not sure the best place to ask this question since there's not a discussion area. Does swift-focuser work properly with SecureField as well? The example in the readme shows a password field but it's a (clear) TextField. Obviously most login screens need this to be a secure field.

    Thanks - hoping the answer is yes as this looks like a great solution to a glaring omission in SwiftUI pre iOS15

    opened by tsfischer 1
  • Requires that 'FormFields' conform to 'FocusStateCompliant'

    Requires that 'FormFields' conform to 'FocusStateCompliant'

    What's wrong with this code?

    enum FormFields {
    	case firstName, lastName, email, password
    }
    
    struct SignUpView: View {
    	@FocusStateLegacy var focusedField: FormFields?
    	@State var firstName = ""
    
    	var body: some View {
    			TextField(
    				"First name",
    				text: $firstName
    			)
    			.focusedLegacy($focusedField, equals: .firstName)
    	}
    }
    

    The issue is "Instance method 'focusedLegacy(_:equals:)' requires that 'FormFields' conform to 'FocusStateCompliant'"

    opened by denis-obukhov 1
  • didBeginEditing called without TapGesture sometimes

    didBeginEditing called without TapGesture sometimes

    I noticed that sometimes TextField get focused without updating focusedField variable. At last, I found sometimes textFieldDidBeginEditing in delegate is called without calling .simultaneousGesture(TapGesture().onEnded block.

    So, I wrote some workaround code.

    Can you review this changes?

    opened by eungkyu 0
  • Softkeyboard appears again when pressing a Toggle on the same view

    Softkeyboard appears again when pressing a Toggle on the same view

    I've got one TextField in my view which gets focus .onAppear. The Done button closes the Softkeyboard correctly. If I'm interacting with any Buttons, Toggles in the same List the last focused TextField gets focus again and the Softkeyboard appears unexpectedly.

    opened by uholland 0
  • fix: Keyboard Glitch / Add automatic conformance to enums that are CaseIterable / Ignore disabled Textfields

    fix: Keyboard Glitch / Add automatic conformance to enums that are CaseIterable / Ignore disabled Textfields

    This PR addresses:

    https://github.com/art-technologies/swift-focuser/issues/6 https://github.com/art-technologies/swift-focuser/issues/8

    And also adds automatic conformance to FocusStateCompliant, so that whoever has an enum that's CaseIterable can conform to FocusStateCompliant and get free implementation instead of doing manual work.

    Update: Implemented skip for disabled Textfield so that it moves to the next field automatically

    opened by tareksabry1337 0
  • Focuser license agreement

    Focuser license agreement

    Hello @AugustDev @JamesRoome, Do you have license (i.e. MIT license) for swift-focuser published somewhere? We want to use it in our project, but can't find a link which should we add.

    Thanks

    opened by akoshkidko 1
  • Soft keyboard appears again when navigating back/forward in navigation view

    Soft keyboard appears again when navigating back/forward in navigation view

    Using Focuser in an input form in a sub view of navigation view, when the keyboard is closed after last input field, tapping on form submit button makes the keyboard open again. Also navigating to previous or next view will have the keyboard displayed shortly on the prev/next view.

    opened by rak-sascha-github 0
Releases(0.2.0)
Owner
Art Technologies
Art Technologies
Autocomplete for a text field in SwiftUI using async/await

Autocomplete for a text field in SwiftUI using async/await

Dmytro Anokhin 13 Oct 21, 2022
Currency text field formatter available for UIKit and SwiftUI 💶✏️

CurrencyText provides lightweight libraries for formating text field text as currency, available for both UIKit and SwiftUI. Its main core, the Curren

Felipe Lefèvre Marino 183 Dec 15, 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
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
AEOTPTextField - A beautiful iOS OTP Text Field library, written in Swift with full access customization in UI.

AEOTPTextField - A beautiful iOS OTP Text Field library, written in Swift with full access customization in UI.

Abdelrhman Kamal 79 Jan 3, 2023
Text entry controls which contain a built-in title/label so that you don't have to add a separate title for each field.

FloatLabelFields Overview Installation Via Interface Builder Via Code Credits Additional References Questions Overview FloatLabelFields is the Swift i

Fahim Farook 1.2k Jan 4, 2023
Floating-textfield-swiftui - Floating textfield swiftui: Floating field with multiple icons

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

Patrick 0 Jan 2, 2022
Easy-to-use token field that is used in the Venmo app.

VENTokenField VENTokenField is the recipients token field that is used in the Venmo compose screen. Installation The easiest way to get started is to

Venmo 797 Dec 6, 2022
SwiftUI TextEdit View - A proof-of-concept text edit component in SwiftUI & CoreText.

A proof-of-concept text edit component in SwiftUI & CoreText. No UIKit, No AppKit, no UITextView/NSTextView/UITextField involved.

Marcin Krzyzanowski 80 Dec 1, 2022
RichTextKit is a Swift-based library for working with rich text in UIKit, AppKit and SwiftUI.

About RichTextKit RichTextKit is a Swift-based library that lets you work with rich text in UIKit, AppKit and SwiftUI. RichTextKit is under developmen

Daniel Saidi 282 Dec 28, 2022
Transition from any SwiftUI Text view into an inline navigation bar title when the view is scrolled off-screen, as seen in Apple's TV & TestFlight iOS apps.

SwiftUI Matched Inline Title Transition from any SwiftUI Text view into an inline navigation bar title when the view is scrolled off-screen, as seen i

Seb Jachec 19 Oct 9, 2022
Render Markdown text in SwiftUI

MarkdownUI MarkdownUI is a library for rendering Markdown in SwiftUI, fully compliant with the CommonMark Spec. Supported Platforms You can use the Ma

Guille Gonzalez 916 Jan 8, 2023
ExpandableText 😎 (SwiftUI) Expand the text with the "more" button

ExpandableText ?? (SwiftUI) Expand the text with the "more" button Get Started import SwiftUI import ExpandableText struct ExpandableText_Test: View

null 35 Dec 26, 2022
Render Markdown text in SwiftUI

Render Markdown text in SwiftUI. It is a preview based on the Marked implementation

小弟调调™ 26 Dec 20, 2022
Declarative text styles and streamlined Dynamic Type support for iOS

StyledText StyledText is a library that simplifies styling dynamic text in iOS applications. Instead of having to use attributed strings every time yo

Blue Apron 233 Oct 18, 2022
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 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
A text view that supports selection and expansion

The Problem UILabel and UITextView offer unsatisfying support for text selection. Existing solutions like TTTAttributedLabel are great but offer a som

Jeff Hurray 636 Dec 20, 2022
Lightweight set of text fields with nice animation and functionality

TweeTextField This is lightweight library that provides different types of Text Fields based on your needs. I was inspired by Jan Henneberg. Features

Oleg 471 Nov 10, 2022