GitHub - RedMadRobot/input-mask-ios: User input masking library repo.
source link: https://github.com/RedMadRobot/input-mask-ios
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
README.md
Description
The library allows to format user input on the fly according to the provided mask and to extract valuable characters.
Mask examples:
- International phone numbers:
+1 ([000]) [000] [00] [00]
- Local phone numbers:
8 ([000]) [000]-[00]-[00]
- Visa card numbers:
[0000] [0000] [0000] [0000]
- Names:
[A][-----------------------------------------------------]
- Text:
[A…]
- Dates:
[00]{/}[00]{/}[9900]
Masks consist of blocks of symbols, which may include:
[]
— a square brackets block for valuable symbols written by user.
Square brackets block may contain any number of special symbols:
0
— mandatory digit. For instance,[000]
mask will allow user to enter three numbers:123
.9
— optional digit . For instance,[00099]
mask will allow user to enter from three to five numbers.А
— mandatory letter.[AAA]
mask will allow user to enter three letters:abc
.а
— optional letter.[АААааа]
mask will allow to enter from three to six letters._
— mandatory symbol (digit or letter).-
— optional symbol (digit or letter).…
— ellipsis. Allows to enter endless count of symbols. For details and rules see Elliptical masks.
Other symbols inside square brackets will cause a mask initialization error, unless you have used custom notations.
Blocks may contain mixed types of symbols; such that, [000AA]
will end up being divided in two groups: [000][AA]
(this happens automatically). Though, it's highly recommended not to mix default symbols with symbols defined by custom notations.
Blocks must not contain nested brackets. [[00]000]
format will cause a mask initialization error.
Symbols outside the square brackets will take a place in the output.
For instance, +7 ([000]) [000]-[0000]
mask will format the input field to the form of +7 (123) 456-7890
.
{}
— a block for valuable yet fixed symbols, which could not be altered by the user.
Symbols within the square and curly brackets form an extracted value (or «valuable characters»).
In other words, [00]-[00]
and [00]{-}[00]
will form the same output 12-34
,
but in the first case the value, extracted by the library, will be equal to 1234
, and in the second case it will result in 12-34
.
Character escaping
Mask format supports backslash escapes when you need square or curly brackets in the output.
For instance, \[[00]\]
mask will allow user to enter [12]
. Extracted value will be equal to 12
.
Note that you've got to escape backslashes in the actual code:
let format: String = "\\[[00]\\]"
Escaped square or curly brackets might be included in the extracted value. For instance, \[[00]{\]}
mask will allow user
to enter the same [12]
, yet the extracted value will contain the latter square bracket: 12]
.
Installation
CocoaPods
pod 'InputMask'
Carthage
git "https://github.com/RedMadRobot/input-mask-ios.git"
Swift Package Manager
dependencies: [ .Package(url: "https://github.com/RedMadRobot/input-mask-ios", majorVersion: 4) ]
Usage
Simple UITextField for the phone numbers
Drop an object on your scene and cofigure it as a MaskedTextFieldDelegate
:
Assign your UITextField.delegate
to be this object:
Make sure your ViewController
knows its residents:
open class ViewController: UIViewController { @IBOutlet weak var listener: MaskedTextFieldDelegate! @IBOutlet weak var field: UITextField! }
Check that your object has configured Primary Mask Format
. Prepare for receiving text changed events by assigning your ViewController
as a delegate
to MaskedTextFieldDelegate
object:
Make your ViewController
to implement MaskedTextFieldDelegateListener
:
open class ViewController: UIViewController, MaskedTextFieldDelegateListener { @IBOutlet weak var listener: MaskedTextFieldDelegate! @IBOutlet weak var field: UITextField! open func textField( _ textField: UITextField, didFillMandatoryCharacters complete: Bool, didExtractValue value: String ) { print(value) } }
All set. Run.
Sample project is located under under Source/Sample
.
Affine masks
You may want to switch between mask formats depending on the user input. Say, most of your phone numbers have primary format like this:
+7 ([000]) [000] [00] [00]
But some of them may have an operator code:
+7 ([000]) [000] [00] [00]#[900]
You put your additional mask formats into the affineFormats
property:
open class ViewController: UIViewController, MaskedTextFieldDelegateListener { @IBOutlet weak var listener: MaskedTextFieldDelegate! open override func viewDidLoad() { super.viewDidLoad() listener.affinityCalculationStrategy = .prefix listener.affineFormats = [ "+7 ([000]) [000] [00] [00]#[900]" ] } }
You may also want to set the affinityCalculationStrategy
. AffinityCalculationStrategy.prefix
configuration works better when your affine formats have distinctive prefixes, e.g. +1 (
and 8 (
, though the default one, .whole
, performs better when the entire value is inserted from the clipboard.
String formatting without views
In case you want to format a String
somewhere in your application's code, Mask
is the class you are looking for.
Instantiate a Mask
instance and feed it with your string, mocking the cursor position:
let mask: Mask = try! Mask(format: "+7 ([000]) [000] [00] [00]") let input: String = "+71234567890" let result: Mask.Result = mask.apply( toText: CaretString( string: input, caretPosition: input.endIndex ), autocomplete: true // you may consider disabling autocompletion for your case ) let output: String = result.formattedText.string
Elliptical masks
[…]
is a wildcard mask, allowing to enter letters and digits. Always returns true
in Result.complete
.
[00…]
is a numeric mask, allowing to enter digits. Requires at least two digits to be complete
.
[9…]
is a numeric mask, allowing to enter digits. Always returns true
in Result.complete
.
[_…]
is a wildcard mask with a single mandatory character. Allows to enter letters and digits. Requires a single character (digit or letter).
[-…]
acts same as […]
.
Elliptical masks support custom notations, too.
Custom notations
An advanced experimental feature. Use with caution.
A floating point number with two decimal places
Custom notations: Results1
123
1234.
1234.5
1234.56
An email (please use regular expressions instead)
With optional and mandatory "dots" and "at" symbol.
Mask: [aaaaaaaaaa][d][aaaaaaaaaa][@][aaaaaaaaaa][d][aaaaaaaaaa][D][aaaaaaaaaa]
d
derh
derh.
derh.a
derh.asd
derh.asd@
derh.asd@h
derh.asd@hello.
[email protected]
[email protected].
[email protected]
[email protected]
An optional currency symbol
Custom notations: Results12
$12
918
€918
1000
$1000
UITextView
support
Known issues
UITextFieldTextDidChange
notification and target-action editingChanged
event
Consider using following workaround in case if you do really need to catch editing events:
Please, avoid at all costs sending SDK events and notifications manually.
Carthage vs. IBDesignables, IBInspectables, views and their outlets
In case you are using our library as a Carthage-built dynamic framework, be aware you won't be able to easily wire your MaskedTextFieldDelegate
objects and their listeners from storyboards in your project. There is a couple of workarounds described in the corresponding discussion, though.
Also, consider filing a radar to Apple, like this one.
Cut action doesn't put text into the pasteboard
When you cut text, characters get deleted yet you won't be able to paste them somewhere as they aren't actually in your pasteboard.
iOS hardwires UIMenuController
's cut action to the UITextFieldDelegate
's textField(_:shouldChangeCharactersIn:replacementString:)
return value. This means "Cut" behaviour actually depends on the ability to edit the text.
Bad news are, our library returns false
in textField(_:shouldChangeCharactersIn:replacementString:)
, and heavily depends on this false
. It would require us to rewrite a lot of logic in order to change this design, and there's no guarantee we'll be able to do so.
Essentially, there's no distinct way to differentiate "Cut selection" and "Delete selection" actions on the UITextFieldDelegate
side. However, you may consider using a workaround, which will require you to subclass UITextField
overriding its cut(sender:)
method like this:
class UITextFieldMonkeyPatch: UITextField { override func cut(_ sender: Any?) { copy(sender) super.cut(sender) } }
From our library perspective, this looks like a highly invasive solution. Thus, in the long term, we are going to investigate a "costly" method to bring the behaviour matching the iOS SDK logic. Yet, here "long term" might mean months.
MaskedTextInputListener
In case you are wondering why do we have two separate UITextFieldDelegate
and UITextViewDelegate
implementations, the answer is simple: prior to iOS 11 UITextField
and UITextView
had different behaviour in some key situations, which made it difficult to implement common logic.
Both had the same bug with the UITextInput.beginningOfDocument
property, which rendered impossible to use the generic UITextInput
protocol UITextField
and UITextView
have in common.
Since iOS 11 most of the things received their fixes (except for the UITextView
edge case). In case your project is not going to support anything below 11, consider using the modern MaskedTextInputListener
.
License
The library is distributed under the MIT LICENSE.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK