Swift plugin which allow add mask to input field

Related tags

Tag AKMaskField
Overview

AKMaskField

Carthage compatible CocoaPods Compatible

Platform Swift Version Build Status License

AKMaskField is UITextField subclass which allows enter data in the fixed quantity and in the certain format (credit cards, telephone numbers, dates, etc.). You only need setup mask and mask template visible for user.

Preview

Features

  • Easy in use
  • Possibility to setup input field from a code or Settings Panel
  • Smart template
  • Support of dynamic change of a mask
  • Fast processing of a input field
  • Smart copy / insert action

Requirements

  • iOS 8.0+
  • Xcode 7.3+

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. To install AKMaskField with CocoaPods:

  1. Make sure CocoaPods is installed.

  2. Update your Podfile to include the following:

    use_frameworks!
    pod 'AKMaskField'
  3. Run pod install.

  1. In your code import AKMaskField like so: import AKMaskField

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To install AKMaskField with Carthage:

  1. Install Carthage via Homebrew

    $ brew update
    $ brew install carthage
  2. Add github "artemkrachulov/AKMaskField" to your Cartfile.

  3. Run carthage update.

  4. Drag AKMaskField.framework from the Carthage/Build/iOS/ directory to the Linked Frameworks and Libraries section of your Xcode project’s General settings.

  5. Add $(SRCROOT)/Carthage/Build/iOS/AKMaskField.framework to Input Files of Run Script Phase for Carthage.

Manual

If you prefer not to use either of the aforementioned dependency managers, you can integrate AKMaskField into your project manually.

  1. Download and drop AKMaskField folder in your project.
  2. Done!

Usage example

Storyboard

Create a text field UITextField and set a class AKMaskField in the Inspector / Accessory Panel tab. Specify necessary attributes in the Inspector / Accessory Attributes tab.

Example:

  • MaskExpression: {dddd}-{DDDD}-{WaWa}-{aaaa}
  • MaskTemplate: ABCD-EFGH-IJKL-MNOP

Programmatically

Setup mask field in your view controller.

var field: AKMaskField!

override func viewDidLoad() {
    super.viewDidLoad()

    field = AKMaskField()
    field.maskExpression = "{dddd}-{DDDD}-{WaWa}-{aaaa}"
    field.maskTemplate = "ABCD-EFGH-IJKL-MNOP"
}

Configuring the Mask Field

var maskExpression: String?

The string value that has blocks with pattern symbols that determine the certain format of input data. Wrap each mask block with proper bracket character.

The predetermined formats:

Mask symbol (pattern) Input format
d Number, decimal number from 0 to 9
D Any symbol, except decimal number
W Not an alphabetic symbol
a Alphabetic symbol, a-Z
. Corresponds to any symbol (default)

Default value of this property is nil.

var maskTemplate: String

The text that represents the mask filed with replacing mask symbol by template character.

Characters count Input format
1 Template character will be copied to each mask block with repeating equal block length.
Equal Template length equal to mask without brackets. Template characters will replace mask blocks in same range.

Default value of this property is *.

func setMask(mask: String, withMaskTemplate maskTemplate: String)

Use this method to set the mask and template parameters.

Parameters

  • maskExpression : Mask (read above).
  • maskTemplate : Mask template (read above).

You can also set default placeholder property. The placeholder will shows only when mask field is clear.

var maskBlockBrackets: AKMaskFieldBrackets

Open and close bracket character for the mask block. Default value of this property is { and }.

Setup Mask Field behavior

var jumpToPrevBlock: Bool { get set }

Jumps to previous block when cursor placed between brackets or before first character in current block. Default value of this property is false.

Accessing the Text Attributes

var text: String? { get set }

The text displayed by the mask field.

Mask Field actions

func refreshMask()

Manually refresh the mask field

Accessing the Delegate

weak var maskDelegate: AKMaskFieldDelegate? { get set }

The receiver’s delegate.

Getting the Mask Field status

var maskStatus: AKMaskFieldStatus { get }

Returns the current status of the mask field. The value of the property is a constant. See AKMaskFieldStatus for descriptions of the possible values.

Getting the Mask Field object

var maskBlocks: [AKMaskFieldBlock] { get }

Returns an array containing all the Mask Field blocks

AKMaskFieldDelegate

Managing Editing

optional func maskFieldShouldBeginEditing(maskField: AKMaskField) -> Bool

Asks the delegate if editing should begin in the specified mask field.

Parameters

  • maskField : The mask field in which editing is about to begin.
optional func maskFieldDidBeginEditing(maskField: AKMaskField)

Asks the delegate if editing should begin in the specified mask field.

Parameters

  • maskField : The mask field in which editing is about to begin.
optional func maskFieldShouldEndEditing(maskField: AKMaskField) -> Bool

Asks the delegate if editing should stop in the specified mask field.

Parameters

  • maskField : The mask field in which editing is about to end.
optional func maskFieldDidEndEditing(maskField: AKMaskField)

Tells the delegate that editing stopped for the specified mask field.

Parameters

  • maskField : The mask field for which editing ended.
optional func maskField(maskField: AKMaskField, didChangedWithEvent event: AKMaskFieldEvent)

Tells the delegate that specified mask field change text with event.

Parameters

  • maskField : The mask field for which event changed.
  • event : Event constant value received after manipulations.

Editing the Mask Field’s Block

optional func maskField(maskField: AKMaskField, shouldChangeBlock block: AKMaskFieldBlock, inout inRange range: NSRange, inout replacementString string: String) -> Bool

Asks the delegate if the specified mask block should be changed.

Parameters

  • maskField : The mask field containing the text.
  • block : Target block. See ** AKMaskFieldBlock** more information.
  • range : The range of characters to be replaced (inout parameter).
  • string : The replacement string for the specified range (inout parameter).

Structures

AKMaskFieldBlock

A structure that contains the mask block main properties.

General

var index: Int

Block index in the mask

var status: AKMaskFieldStatus { get }

Returns the current block status.

var chars: [AKMaskFieldBlockCharacter]

An array containing all characters inside block. See AKMaskFieldBlockCharacter structure information.

Pattern

var pattern: String { get }

The mask pattern that represent current block.

var patternRange: NSRange { get }

Location of the mask pattern in the mask.

Mask template

var template: String { get }

The mask template string that represent current block.

var templateRange: NSRange { get }

Location of the mask template string in the mask template.

AKMaskFieldBlockCharacter

A structure that contains the block character main properties.

General

var index: Int

Character index in the block.

var blockIndex: Int

The block index in the mask.

var status: AKMaskFieldStatus

Current character status.

Pattern

var pattern: AKMaskFieldPatternCharacter

The mask pattern character. See AKMaskFieldPatternCharacter costant information.

var patternRange: NSRange

Location of the pattern character in the mask.

Mask template

var template: Character

The mask template character.

var templateRange: NSRange

Location of the mask template character in the mask template.

Constants

AKMaskFieldStatus

enum AKMaskFieldStatus {
	case Clear
	case Incomplete
	case Complete
}

The Mask Field, Block and Block Character status property constant.

AKMaskFieldEvent

enum AKMaskFieldEvet {
	case None
	case Insert
	case Delete
	case Replace
}

Event constant value received after manipulations with the Mask Field.

AKMaskFieldPatternCharacter

enum AKMaskFieldPatternCharacter: String {
  case NumberDecimal = "d"
  case NonDecimal = "D"
  case NonWord = "W"
  case Alphabet = "a"
  case Any = "."
}

Single block character pattern constant.

Constatns

  • NumberDecimal : Number, decimal number from 0 to 9
  • NonDecimal : Any symbol, except decimal number
  • NonWord : Not an alphabetic symbol
  • Alphabet : Alphabetic symbol, a-Z
  • Any : Corresponds to any symbol (default)
func pattern() -> String

Returns regular expression pattern.

Contribute

Please do not forget to ★ this repository to increases its visibility and encourages others to contribute.

Got a bug fix, or a new feature? Create a pull request and go for it!

Meta

Artem Krachulov – www.artemkrachulov.com - [email protected]

Released under the MIT license

https://github.com/artemkrachulov

Comments
  • Getting: fatal error: can not increment endIndex

    Getting: fatal error: can not increment endIndex

    I am getting the error: fatal error: can not increment endIndex when I move out of a masked field into an unmasked field. The culprit is in the convertRange method.

    public func convertRange(range: Range<Int>) -> Range<String.Index> {
    
        let startIndex = advance(self.startIndex, range.startIndex)
        let endIndex = advance(startIndex, range.endIndex - range.startIndex)
    
        return Range<String.Index>(start: startIndex, end: endIndex)
    }
    

    My text field is basic:

    phoneContactField.placeholder = "Enter your phone number"
    phoneContactField.textAlignment = .Center
    phoneContactField.font = UIFont.caFontWithSize(18)
    phoneContactField.delegate = self
    phoneContactField.mask = "({ddd}) {ddd}-{dddd}"
    phoneContactField.maskDelegate = self
    phoneContactField.maskTemplate = "(XXX) XXX-XXXX"
    phoneContactField.maskShowTemplate = true
    

    Any thoughts?

    opened by t2 8
  • maskDelegate is inaccessible

    maskDelegate is inaccessible

    Hi I try to trigger the .ValueChanged on AKMaskField but as soon as i set maskExpression the event is not trigger anymore. therefore i tried to set the delegate and i have this error

    'maskDelegate' is inaccessible due to 'internal' protection level

    valueField.maskDelegate = self
    valueField.text = value
    

    I use the swift3 branch.

    Thanks, Have a good day.

    opened by jeremypiednoel 6
  • AKMaskField was deallocated while key value observers were still registered with it.

    AKMaskField was deallocated while key value observers were still registered with it.

    Hello,

    When navigationController?.popViewControllerAnimated(true) runs, error occurs. How can I fix it? I think it occurs because of manual updating part but I need that part.

    Thanks

    Error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7f81104aafc0 of class MyMobileProject.AKMaskField was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x7f811292c560> ( <NSKeyValueObservance 0x7f8112925510: Observer: 0x7f81104aafc0, Key path: text, Options: <New: NO, Old: NO, Prior: NO> Context: 0x0, Property: 0x7f8112924000>

    opened by loplopLover 5
  • Challenge getting mask to work.

    Challenge getting mask to work.

    I am receiving an error "Use of undeclared type 'AKMaskField'" i swift on a project I am working on. I have downloaded the project and copied it to my project folder. any ideas of challenge?

    opened by davestucky 2
  • mask isn't automatically applied if text is programmatically set

    mask isn't automatically applied if text is programmatically set

    If you put the following line into the Demo's viewDidLoad code, it does not autoformat the text.

        card.text = "1234123412341234"
    

    Is there a way to force it to trigger the mask?

    opened by sabernar 2
  • Mask Template doesn't seem correctly

    Mask Template doesn't seem correctly

    Hello again,

    I set textfield mask template like as XXX-XXXXXX; however, when I start application, it seems *** - ******. How can I fix it? Also I wonder how can I control that all fields are completed or not?

        switch maskField.maskStatus {
        case .Clear:
            statusColor = UIColor(red: 241/255, green: 241/255, blue: 241/255, alpha: 1.0)
        case .Incomplete:
            saveButton.backgroundColor = UIColor(red: 123/255, green: 166/255, blue: 55/255, alpha: 0.6)
            saveButton.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
        case .Complete:
            saveButton.backgroundColor = UIColor(red: 123/255, green: 166/255, blue: 55/255, alpha: 1.0)
            saveButton.addTarget(self, action: "sendJson:", forControlEvents: UIControlEvents.TouchUpInside)
        default:
            statusColor = UIColor.clearColor()
        }
    

    In this example, I have 3 fields and complete case works for each of them at different time. I want to make a case like as complete to control all fields at same time. If all fields are not empty then complete case works.

    Best regards,

    Haydar

    opened by loplopLover 2
  • Swift 3 xCode 8.3.2  Does not launch Simulator

    Swift 3 xCode 8.3.2 Does not launch Simulator

    Downloaded App. When I open the sample project and then build to run untouched the simulator does not load or run for this app. What's missing or needs to be changed. Would like to use this code but hard to eval if the sample code is not working.

    opened by OpExNetworks 1
  • Use of undeclared type 'AKMaskField'

    Use of undeclared type 'AKMaskField'

    OK What am I doing incorrectly? I am still getting the error listed above. I copied the folder AKMaskField into my project and saved it. Still getting error..

    opened by davestucky 1
  • Carthage support

    Carthage support

    opened by TofPlay 1
  • Marked public methods as required

    Marked public methods as required

    Default declaration for variables and functions is internal in Swift. When using AKMaskView as a library, it's impossible to reach some required variables inside the project because the have not defined public. I have marked some variables and functions public to be able to work with them.

    I have checked README and tried to mark all mentioned variables and functions as public but I might have missed some. If you see something missing please let me know and I can add. This also fixes issue #14.

    opened by cemaleker 1
  • Crash on method Refresh()

    Crash on method Refresh()

    Original Code

        func refresh() {
    
            if maskObject.count > 0 && maskText != text {
                text = maskShowTemplate ? maskText : maskStatus == .Clear ? "" : maskText
            }
    
            // Reset manual updating property flag
            flagUpdateEvent = true
        }
    
    

    The object maskObject was missing the Optional symbol(?) because it can be nil Solution

        func refresh() {
    
            if maskObject?.count > 0 && maskText != text {
                text = maskShowTemplate ? maskText : maskStatus == .Clear ? "" : maskText
            }
    
            // Reset manual updating property flag
            flagUpdateEvent = true
        }
    
    opened by KaMagno 1
  • Deleting written character right away

    Deleting written character right away

    I am not really sure whether it is an issue, but will post it here. Apologies if it does not meet guidelines.

    When deleting characters of AKMaskField, characters other than those which are specified in maskExpression do not get deleted, which is ok. But in order to reach the needed character to delete, the spaces and "not-written" characters (such as '/') still make you press delete button pass them. Is there any feature which allows you to delete written character (jump into the written character when deleting) right away? (video attached)

    1

    opened by mamadnazar 0
  • MaskField in cell reloading

    MaskField in cell reloading

    When table view cell will display with textField AkMaskFieldDelegate calls func maskField(_ maskField: AKMaskField, didChangedWithEvent event: AKMaskFieldEvent) with empty string Should not call this func when reloading

    opened by Nurka11 0
Owner
Artem Krachulov
Artem Krachulov
An iOS text field that represents tags, hashtags, tokens in general.

WSTagsField An iOS text field that represents tags, hashtags, tokens in general. Usage let tagsField = WSTagsField() tagsField.layoutMargins = UIEdgeI

Whitesmith 1.2k Jan 9, 2023
UIScrollView subclass that allows to add a list of highly customizable tags.

UIScrollView subclass that allows to add a list of highly customizable tags. You can customize colors, border radius, and the tail of the tag. Tags ca

Andrea Mazzini 765 Nov 19, 2022
Made in Swift - Tag layout for UICollectionView supporting 3 types of alignments - Left || Centre || Right

TagCellLayout About Its an ui-collection-view LAYOUT class that takes care of all the logic behind making tags like layout using UICollectionView. It

Ritesh Gupta 346 Jan 1, 2023
Simple and highly customizable iOS tag list view, in Swift.

TagListView Simple and highly customizable iOS tag list view, in Swift. Supports Storyboard, Auto Layout, and @IBDesignable. Usage The most convenient

Ela Workshop 2.5k Dec 28, 2022
🔍 Awesome fully customize search view like Pinterest written in Swift 5.0 + Realm support!

YNSearch + Realm Support Updates See CHANGELOG for details Intoduction ?? Awesome search view, written in Swift 5.0, appears search view like Pinteres

Kyle Yi 1.2k Dec 17, 2022
Simple and highly customizable iOS tag list view, in Swift.

TagListView Simple and highly customizable iOS tag list view, in Swift. Supports Storyboard, Auto Layout, and @IBDesignable. Usage The most convenient

Ela Workshop 2.5k Dec 31, 2022
Input Mask is an Android & iOS native library allowing to format user input on the fly.

Migration Guide: v.6 This update brings breaking changes. Namely, the autocomplete flag is now a part of the CaretGravity enum, thus the Mask::apply c

red_mad_robot 548 Dec 20, 2022
VMaskTextField is a library which create an input mask for iOS.

VMaskTextField An inputmask helps the user with the input by ensuring a predefined format. This can be useful for dates, numerics, phone numbers etc U

Vinícius Oliveira 384 Jul 20, 2022
Input Validation Done Right. A Swift DSL for Validating User Input using Allow/Deny Rules

Valid Input Validation Done Right. Have you ever struggled with a website with strange password requirements. Especially those crazy weird ones where

Mathias Quintero 37 Nov 3, 2022
TCDInputView is an open source custom input view which is displayed when a text field becomes the first responder.

TCDInputView for iOS TCDInputView is an open source custom input view which is displayed when a text field becomes the first responder. Requirements T

Tom Diggle 7 Apr 25, 2016
A passcode entry field for macOS similar to Apple's two-factor authentication field.

DSFPasscodeView A passcode entry field for macOS similar to Apple's two-factor authentication field. About The control is made up of multiple groups o

Darren Ford 10 Nov 12, 2022
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
In-app notification in Swift, with customizable buttons and input text field.

Notie Undistracted in-app notification in Swift, with added buttons and input box. Installation CocoaPods To integrate Notie into your Xcode project u

Thi Doãn 85 Aug 8, 2020
Highly customizable iOS tags view [input, edit, dynamic, tag, token, field, NSTokenField]

RKTagsView Highly customizable iOS tags view (like NSTokenField). Supports horizontal and vertical direction, editing, multiple selection, Auto Layout

Roman Kulesha 450 Oct 2, 2022
A plugin to allow Lightroom to export HEIC files

LRExportHEIC A plugin to allow Lightroom to export HEIC files. There are two components: The plugin itself, which is the component that interfaces wit

Manu Wallner 21 Jan 3, 2023
Swift Library based on AVFoundation that allow to easily add camera feature with custom UI into your project.

Would you like to create your camera same as Snapchat or Instagram? I think this library could help you. Basicly it is a wrapper above AVFoundation th

Taras Chernyshenko 14 Sep 21, 2022
Allow to add .pkpass files to Apple wallet

Allow to add .pkpass file to Apple Wallet

Jose Valentin Abundo Hernandez 4 Nov 11, 2022
Animated Mask Label is a nice gradient animated label.

Animated Mask Label Demo Screen Screenshot Demo/Example For demo: $ pod try AnimatedMaskLabel To run the example project, clone the repo, and run pod

Jogendra 19 Dec 13, 2022
A segment switcher with dynamic text mask effect

DynamicMaskSegmentSwitch A segment switcher with dynamic text mask effect ##Preview: Indicator will bounce when progress less than 0 or larger than 1.

Qitao Yang 309 Oct 7, 2022
A prototype of custom tab bar using SwiftUI with techniques of mask + matchedGeometryEffect

SliderTabBar A prototype of custom tab bar using SwiftUI with techniques of mask

Ka Kui 1 Dec 24, 2021