Skip to content

Latest commit

 

History

History
312 lines (233 loc) · 15.6 KB

Documentation.md

File metadata and controls

312 lines (233 loc) · 15.6 KB

Documentation

CurrencyFormatter is CurrencyText's core. It is a wrapper around NumberFormatter with currency number style, that provides API for formatting content as/from currency, and can be used both in isolation, injected into CurrencyUITextFieldDelegate for UIKit text field, or passed in to a CurrencyTextField in SwiftUI.

Creating a CurrencyFormatter instance is pretty simple; you can use the builder pattern approach where the init class require a callback in which the self instance is passed, allowing you to configure your properties by keeping the code clean and readable (Inspired by SwiftRichString):

let formatter = CurrencyFormatter {
  $0.currency = .euro
  // set any other attribute available on CurrencyFormatter public API
}

let formattedString = formatter.string(from: 30.0) //€30.00

To change the currency style (symbol, formatting, separators) you must make use of .currency and .locale properties. By default such properties are configured based on the user's system configurations, deriving the currency format from the user current locale (Locale.autoUpdating). Therefore only set these properties in cases where you want granular control over how the currency is formatted, e.g. always in currency.dollar with CurrencyLocale.englishUnitedStates.

All locales were extracted from jacobbubu - ioslocaleidentifiers

CurrencyLocale is a String backed enum that wraps all available Locale identifiers. CurrencyFormatter's locale property can be set by passing a common system Locale or one of CurrencyLocale's cases, such as .italian, .danish or .chinese. Note that you can set locale and compose it with a different currency of your choice, what is going to change is generally only the currency symbol.

public enum CurrencyLocale: String, LocaleConvertible {
    
    case current = "current"
    case autoUpdating = "currentAutoUpdating"
    
    case afrikaans = "af"
    case afrikaansNamibia = "af_NA"
    case afrikaansSouthAfrica = "af_ZA"
    //...
}

Currency type is also a String backed enum that matches all available currency codes, while keeping a type safe / simple API for setting currencies (e.g. .euro, .dollar or .brazilianReal).

public enum Currency: String {
    case afghani = "AFN",
    algerianDinar = "DZD",
    argentinePeso = "ARS"
    //...
}

Note that defining currency does not always goes as planned, because the most part of the format generally changes accordingly to user locale. For example, setting .euro as currency but with default user locale (Brazil), has the euro's currency symbol with separators and remaining style as used in Brazil.

let formatter = CurrencyFormatter {
  $0.currency = .dollar
  $0.locale = CurrencyLocale.englishUnitedStates
}

let formattedString = formatter.string(from: 30.0) //$30.00

Therefor prioritize setting locale in case you have a custom setup, and only update currency whenever you want to have full control of the format configuration.

For those cases where your design requires a custom presentation don't worry because the formatter is heavily customizable. For example decimals can be removed, maximum and minimum allowed values can be set, grouping size can be customized or even a hole new currency symbol can be defined. It is all up to you and your use case:

let formatter = CurrencyFormatter {
  $0.hasDecimals = false
  $0.maxValue = 999999
  $0.groupingSize = 2
  $0.groupingSeparator = ";"
  $0.currencySymbol = "💶"
}

let formattedString = formatter.string(from: 100000000) //💶99;99;99

The UIKit library provides an easy to use and extendable UITextFieldDelegate that can be plugged to any text field without the need to use a specific UITextField subclass 😉.

CurrencyTextFieldDelegate is a type that inherits from UITextFieldDelegate, and provide a simple interface to configure how the inputs are configured as currency.

To start formatting user's input as currency, you need to initialize a CurrencyTextFieldDelegate instance passing in a currency formatter configured as you wish, and then set it as the text field's delegate.

let currencyFormatter = CurrencyFormatter()
textFieldDelegate = CurrencyUITextFieldDelegate(formatter: currencyFormatter)
textFieldDelegate.clearsWhenValueIsZero = true

textField.delegate = textFieldDelegate

Just by setting a currency text field delegate object to your text field, with given formatter behavior, the user inputs are going to be formatted as expected.

The passthroughDelegate property availble on CurrencyTextFieldDelegate instances, can be used to listen and pottentially handle UITextFieldDelegate events that are sent to CurrencyUITextFieldDelegate. It can be useful to intercept the delegate calls when e.g. for when tracking analytics events.

But be aware and make sure the implementation of this object does not wrongly interfere with currency formatting, e.g. by returning false ontextField(textField:shouldChangeCharactersIn:replacementString:) no currency formatting is done.

let currencyTextFieldDelegate = CurrencyUITextFieldDelegate(formatter: currencyFormatter)
currencyTextFieldDelegate.passthroughDelegate = selfTextFieldDelegateListener

textField.delegate = currencyTextFieldDelegate

// all call to `currencyTextFieldDelegate` `UITextField` delegate methods will be forwarded to `selfTextFieldDelegateListener`.

If you want your users to be able to input negative values just set textField's keyboardType to .numbersAndPunctuation, so whenever users tap the negative symbol it will be correctly presented and handled.

textField.keyboardType = .numbersAndPunctuation

// users inputs "-3456"
// -R$ 34.56

The following properties are available:

PROPERTY TYPE DESCRIPTION
locale LocaleConvertible Locale of the currency
currency Currency Currency used to format
currencySymbol String String shown as currency symbol
showCurrencySymbol Bool Show/hide currency symbol
minValue Double? The lowest number allowed as input
maxValue Double? The highest number allowed as input
decimalDigits Int The number of decimal digits shown
hasDecimals Bool? Decimal digits are shown or not
decimalSeparator String Text used to separate the decimal digits
currencyCode String Currency raw code value
alwaysShowsDecimalSeparator Bool Shows decimal separator even when there are no decimal digits
groupingSize Int The amount of grouped numbers
secondaryGroupingSize Int The amount of grouped numbers after the first group
groupingSeparator String String that is shown between groups of numbers
hasGroupingSeparator Bool Adds separator between all group of numbers
maxIntegers Int Maximum allowed number of integers
maxDigitsCount Int Returns the maximum amount of digits (integers + decimals)
zeroSymbol String Text shown when string's value is equal zero

CurrencyText can also be used on SwiftUI via library introduced from the version 2.2.0. Due to limitations on SwiftUI SDKs, like defining the selected text range, the UIKit version of the library was brigded to SwiftUI via UIViewRepresentable - more on the limitations can be seen in the implementation PR description. This may change in the future whenever the same functionality can be provided on vanilla SwiftUI.

CurrencyTextField is a SwiftUI.View that formats user inputs as currency based on a given CurrencyTextFieldConfiguration. The configuration holds a CurrencyFormatter with all format related setup, bindings for text, closures for reacting to key text field events, and a configuration block for setting the looks and behavior of the underlying UITextField.

var body: some View {
   CurrencyTextField(
      configuration: .init(
         placeholder: "Play with me...",
         text: $viewModel.data.text,
         unformattedText: $viewModel.data.unformatted,
         inputAmount: $viewModel.data.input,
         clearsWhenValueIsZero: true,
         formatter: .default,

         // The configuration block allows defining the looks 
         // and doing additional configuration to
         // the underlying UITextField.
         // This is needed given that for most `SwiftUI` 
         // modifiers there's no API for converting
         // back to UIKit - e.g. `Font` is not transformable to `UIFont`.
         textFieldConfiguration: { uiTextField in
            uiTextField.borderStyle = .roundedRect
            uiTextField.font = UIFont.preferredFont(forTextStyle: .body)
            uiTextField.textColor = .blue
            uiTextField.layer.borderColor = UIColor.red.cgColor
            uiTextField.layer.borderWidth = 1
            uiTextField.layer.cornerRadius = 4
            uiTextField.keyboardType = .numbersAndPunctuation
            uiTextField.layer.masksToBounds = true
         },
         onEditingChanged: { isEditing in
            if isEditing == false {
               // How to programmatically clear the text of CurrencyTextField:
               // The Binding<String>.text that is passed 
               // into CurrencyTextField.configuration can
               // manually cleared / updated with an empty String
               clearTextFieldText()
            }
         },
         onCommit: {
            // do something when users have committed their inputs
         }
      )
   )
}

For more details on specifics please refer to the code documentation and SwiftUIExampleView in the ExampleApp.

CurrencyTextField is bridged from UIKit to SwiftUI via UIViewRepresentable, it isn't a vanilla SwiftUI.TextField and thus does not have native focused support.

In order to control and observe the focus/isFirstResponder one can pass a Biniding<Bool?> when configuring a CurrencyTextField, which can be initially set as true if the text field should appear selected.

struct MyView: View {
    @State private var hasFocus: Bool?
    @State private var text = ""

    var body: some View {
        CurrencyTextField(
            configuration: .init(
                text: $text,
                hasFocus: $hasFocus,
                // ...
            )
        )
        .onAppear {
            hasFocus = true
        }
    }
}

For more details on specifics please refer to the code documentation and SwiftUIExampleView in the ExampleApp.

As a matter of context, the strategy of bridging the UIKit implementation to SwiftUI via UIViewRepresentable was chosen since there's no API yet for controlling a SwiftUI.TextFields .selectedTextRange, which is needed in CurrencyText for cases e.g. where the currency symbol is at the end and to provide the best user experience the text field has to auto update the .selectedTextRange to be before the currency symbol.

With that scenario in mind, and understanding that CurrencyTextField uses UITextField internally, the easiest way to allow users to fully control the component was to give them access to the underlying UITextField instance so it could be configured and setup accordingly to their needs.

As alternative it was considered wrapping UIKit.UITextFields API, but that layer would be both extra work to develop and confusing for users, given that most of us (Apple third-party developers) are already familiar with UIKit.UITextField's API. Besides that, the framework would never build for other platforms given that

Connected to what was mentioned above, the SwiftUI library currently bridges the UIKit implementation and that limits the framework on building only for iOS.

Thoughts for the future

#79