UITextField subclass with autocompletion suggestions list

Overview

alt_tag

SearchTextField

Version License Platform

Overview

SearchTextField is a subclass of UITextField, written in Swift that makes really easy the ability to show an autocomplete suggestions list.
You can decide wether to show the list as soon as the field is focused or when the user starts typing.
You can also detects when the user stops typing, very useful when you can get a suggestion list from a remote server.

New Feature! Now you can make suggestions "inline", showing the first matched result as the placeholder (instead of the results list) and selecting it when the user touches the enter key.


alt_tag

Requirements

  • iOS 9

Installation

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

use_frameworks!

pod "SearchTextField"

Manual installation

Just import SearchTextField.swift into your project

Usage

You can use it in the simplest way...

import SearchTextField

// Connect your IBOutlet...
@IBOutlet weak var mySearchTextField: SearchTextField!

// ...or create it manually
let mySearchTextField = SearchTextField(frame: CGRectMake(10, 100, 200, 40))

// Set the array of strings you want to suggest
mySearchTextField.filterStrings(["Red", "Blue", "Yellow"])

...or you can customize it as you want

// Show also a subtitle and an image for each suggestion:

let item1 = SearchTextFieldItem(title: "Blue", subtitle: "Color", image: UIImage(named: "icon_blue"))
let item2 = SearchTextFieldItem(title: "Red", subtitle: "Color", image: UIImage(named: "icon_red"))
let item3 = SearchTextFieldItem(title: "Yellow", subtitle: "Color", image: UIImage(named: "icon_yellow"))
mySearchTextField.filterItems([item1, item2, item3])

// Set a visual theme (SearchTextFieldTheme). By default it's the light theme
mySearchTextField.theme = SearchTextFieldTheme.darkTheme()

// Modify current theme properties
mySearchTextField.theme.font = UIFont.systemFontOfSize(12)
mySearchTextField.theme.bgColor = UIColor (red: 0.9, green: 0.9, blue: 0.9, alpha: 0.3)
mySearchTextField.theme.borderColor = UIColor (red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
mySearchTextField.theme.separatorColor = UIColor (red: 0.9, green: 0.9, blue: 0.9, alpha: 0.5)
mySearchTextField.theme.cellHeight = 50

// Set specific comparision options - Default: .caseInsensitive
mySearchTextField.comparisonOptions = [.caseInsensitive]

// Set the max number of results. By default it's not limited
mySearchTextField.maxNumberOfResults = 5

// You can also limit the max height of the results list
mySearchTextField.maxResultsListHeight = 200

// Customize the way it highlights the search string. By default it bolds the string
mySearchTextField.highlightAttributes = [NSBackgroundColorAttributeName: UIColor.yellowColor(), NSFontAttributeName:UIFont.boldSystemFontOfSize(12)]

// Handle what happens when the user picks an item. By default the title is set to the text field
mySearchTextField.itemSelectionHandler = {item, itemPosition in
    mySearchTextField.text = item.title
}

// You can force the results list to support RTL languages - Default: false
mySearchTextField.forceRightToLeft = true

// Show the list of results as soon as the user makes focus - Default: false
mySearchTextField.startVisible = true

// ...or show the list of results even without user's interaction as soon as created - Default: false
mySearchTextField.startVisibleWithoutInteraction = true

// Start filtering after an specific number of characters - Default: 0
mySearchTextField.minCharactersNumberToStartFiltering = 3

// Force to show the results list without filtering (but highlighting)
mySearchTextField.forceNoFiltering = true

// Explicitly hide the results list
mySearchTextField.hideResultsList()

/**
* Update data source when the user stops typing.
* It's useful when you want to retrieve results from a remote server while typing
* (but only when the user stops doing it)
**/
mySearchTextField.userStoppedTypingHandler = {
    if let criteria = self.mySearchTextField.text {
        if criteria.characters.count > 1 {

            // Show the loading indicator
            self.mySearchTextField.showLoadingIndicator()

            self.searchMoreItemsInBackground(criteria) { results in
                // Set new items to filter
                self.mySearchTextField.filterItems(results)

                // Hide loading indicator
                self.mySearchTextField.stopLoadingIndicator()
            }
        }
    }
}

// Handle item selection - Default behaviour: item title set to the text field
mySearchTextField.itemSelectionHandler = { filteredResults, itemPosition in
    // Just in case you need the item position
    let item = filteredResults[itemPosition]
    print("Item at position \(itemPosition): \(item.title)")

    // Do whatever you want with the picked item
    self.mySearchTextField.text = item.title
}

// Define a results list header - Default: nothing
let header = UILabel(frame: CGRect(x: 0, y: 0, width: acronymTextField.frame.width, height: 30))
header.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
header.textAlignment = .center
header.font = UIFont.systemFont(ofSize: 14)
header.text = "Pick your option"
mySearchTextField.resultsListHeader = header


New feature: show the first matched result as placeholder (inline mode)

// Set the array of strings you want to suggest
mySearchTextField.filterStrings(["Red", "Blue", "Yellow"])

// Then set the inline mode in true
mySearchTextField.inlineMode = true

New feature: autocomplete from, for example, a list of email domains

emailInlineTextField.inlineMode = true
emailInlineTextField.startFilteringAfter = "@"
emailInlineTextField.startSuggestingInmediately = true
emailInlineTextField.filterStrings(["gmail.com", "yahoo.com", "yahoo.com.ar"])

Swift Versions

Swift 5 supported from 1.2.3 version.

Swift 4 supported from 1.2.0 version.

Install v1.0.0 if you need to support Swift 2.3.

Install v1.0.2 and above if you want to support Swift 3.

Demo

Check out the Example project.

Author

Alejandro Pasccon, [email protected]

License

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

Comments
  • received thread error EXC_BAD_ACCESS

    received thread error EXC_BAD_ACCESS

    to reproduce:

    opened new Xcode project installed pod ver 1.0.10

    code in view controller:

    import UIKit import SearchTextField

    class ViewController: UIViewController {

    @IBOutlet weak var mySearchTextField: SearchTextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
       
        
        // Set the array of strings you want to suggest
        mySearchTextField.filterStrings(["Red", "Blue", "Yellow"])
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    }

    opened by yv2link 12
  • when i used two UITextField which is inherited from SearchTextField it will not show the search result in Xcode 9.0

    when i used two UITextField which is inherited from SearchTextField it will not show the search result in Xcode 9.0

    Hello, I updated Xcode to 9.0 and I stuck with one new problem.

    ## ex. when I search any city name is will not show me a drop-down list [as I install pod i.e. SearchTextField]. please help me to solved above problem?

    After update done, I again install pod as per given on cocoapods website but still, I get the error.

    but before updating Xcode it will be working fine, so what should I do now? Please, Help me...!

    opened by kiraninfogird 10
  • Question: Anyway to compare on

    Question: Anyway to compare on "somestring"@

    Is there anyway to suggest as soon as @ is pressed after some string. I want to suggest some email domains

    self.inputField.filterStrings(["@gmail.com", "@hotmail.com"])

    opened by tristangrichard 9
  • use of unresolved identifier NSAttributedStringKey

    use of unresolved identifier NSAttributedStringKey

    Hi i am using swift 3 But getting message use of unresolved identifier NSAttributedStringKey when i run the code. I have used manual integration. Just imported your .swift file Plase help

    Thanks

    opened by muga87 8
  • font style not working properly issue

    font style not working properly issue

    had modify the font size to 18 by using. "emailTextField.theme.font = UIFont.systemFont(ofSize: 18)". The suggestion character which consists in my emailtextfield still remain the default size while other character become 18.

    opened by aznelite89 7
  • Could not change theme font

    Could not change theme font

    In SearchTextFieldTheme we can't set custom font For example when I use UIFont(name: "BNazanin", size: 10)! in init of SearchTextFieldTheme the tableview does not appear for suggestion

    opened by arashetm 7
  • Dropdown not appearing on newest version

    Dropdown not appearing on newest version

    Hey great framework here. I was testing the version you released yesterday. The dropdown with options does not seem to appear anymore. I implemented the simple example and also pulled down and ran your example project and no dice. The new feature "show the first matched result as placeholder (inline mode)" works great though.

    opened by davidthurman 7
  • Is possible to pass a hidden field in the SearchTextFieldItem like an user ID?

    Is possible to pass a hidden field in the SearchTextFieldItem like an user ID?

    Whats is the best way to pass a user id to a variable as people use SearchTextField, since SearchTextFieldItem has only 3 param, how can I pass a hidden param of find the user id comparing the SearchTextFieldItem to a User List = Users or user the users list as a SearchTextFieldItem with hidden params.

    opened by Rovel 5
  • Feature Request: SearchTextFieldItem as protocol or extendable class

    Feature Request: SearchTextFieldItem as protocol or extendable class

    I would really like to store some meta-data in the SearchTextFieldItems, so that I can access that data when the item is selected.

    Example: mix suggestions from various sources, and then when the user clicks, immediately know the source.

    Seems pretty straightforward to me :-)

    opened by btanner 5
  • Thread 1: EXC_BAD_ACCESS (code=2, address=0x1064b2e58)

    Thread 1: EXC_BAD_ACCESS (code=2, address=0x1064b2e58)

    Hi, when i run my project i get this Error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x1064b2e58)"

    and my code is `class provider: UIViewController {

    @IBOutlet weak var mySearchTextField: SearchTextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
     
        mySearchTextField.filterStrings(["Red", "Blue", "Yellow"])
    }
    `
    
    opened by hokage4 4
  • Xcode 9 errors

    Xcode 9 errors

    *Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font' *Type 'NSAttributedStringKey' (aka 'NSString') has no member 'foregroundColor' *Cannot convert value of type '[NSAttributedStringKey : AnyObject]' (aka 'Dictionary<NSString, AnyObject>') to expected argument type '[String : Any]?'

    opened by arashetm 3
  • How to use this on viewController instead of UITableViewController

    How to use this on viewController instead of UITableViewController

    I have implemented this module and works everything except the tableView didSelectItemat it never gets called ! Can someone please let me know the solution Thank you in advance!

    opened by mohitkokwani 0
  • Fix empty placeholder crash, and remove deprecated method from iOS 13

    Fix empty placeholder crash, and remove deprecated method from iOS 13

    When the placeholder for the textfield is set to an empty string (textField.placeholder = ""). In the buildPlaceholderLabel() method, using attribute(.foregroundColor, at: 0, effectiveRange: nil) for an empty string will cause crash.

                if let placeholderColor = self.attributedPlaceholder?.attribute(NSAttributedString.Key.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
                    placeholderLabel?.textColor = placeholderColor
                }
    

    So I add the code to check if the attributedPlaceholder is empty before calling attribute() method.

                if let attributedPlaceholder = self.attributedPlaceholder, attributedPlaceholder.length > 0,
                   let placeholderColor = attributedPlaceholder.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
                    placeholderLabel?.textColor = placeholderColor
                }
    

    This branch also merge @pateldhruvil96 's fix for Swift Package Manager support, and remove deprecated method from iOS 13.

    opened by benck 0
  • Not visible when text is too long

    Not visible when text is too long

    When text is very long. How can we show the full text ? Right now, it's ending with ... (triple dot)

    For ex- The real text is Coimbatore Chinna Swami Muthu Swami Venu Gopal lyer. But it's showing Coimbatore Chinna Swami Mut... There is lots of name like this, so all text seems to be same.

    Please let me know the solution. Thanks

    opened by amankumarchoudhary 1
Owner
Alejandro Pasccon
Alejandro Pasccon
Subclass of UITextField that shows inline suggestions while typing.

AutocompleteField Subclass of UITextField that shows inline suggestions while typing. Plug and play replacement for UITextField. Delimiter support. Pe

Filip Stefansson 663 Dec 6, 2022
ARAutocompleteTextView is a subclass of UITextView that automatically displays text suggestions in real-time

ARAutocompleteTextView is a subclass of UITextView that automatically displays text suggestions in real-time. This is perfect for automatically suggesting the domain as a user types an email address, #hashtag or @alexruperez.

Alex Rupérez 261 Jun 29, 2022
An UITextField subclass to simplify country code's picking. Swift 5.0

Preview Installation NKVPhonePicker is available through CocoaPods. To install it, simply add the following line to your Podfile: pod 'NKVPhonePicker'

Nike Kov 140 Nov 23, 2022
Animated Subclass of UITextField created with CABasicAnimation and CAShapeLayer

JDAnimatedTextField JDAnimatedTextField is animateable UITextField that can significantly enhance your user's experiences and set your app apart from

Jawad Ali 25 Dec 13, 2022
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 subclass with autocomplete menu. For iOS.

MLPAutoCompleteTextField "We believe that every tap a user makes drains a tiny bit of their energy and patience. Typing is one of the biggest expendit

Eddy Borja 1.2k Nov 11, 2022
HTYTextField A UITextField with bouncy placeholder.

HTYTextField - A UITextField with bouncy placeholder. Screenshot Installation CocoaPods Add the dependency to your Podfile

Hanton Yang 312 Nov 13, 2022
Fully-wrapped UITextField made to work entirely in SwiftUI

iTextField ⌨️ A fully-wrapped `UITextField` that works entirely in SwiftUI. ?? Get Started | Examples | Customize | Install | Get Started Install iTex

Benjamin Sage 89 Jan 2, 2023
UITextField character counter with lovable UX 💖. No math skills required 🙃.

TextFieldCounter UITextField character counter with lovable UX ??. No math skills required ??. Features Set max length of UITextField. A beautiful an

Fabricio Serralvo 434 Dec 22, 2022
🏄‍♂️ UITextField-Navigation makes it easier to navigate between UITextFields and UITextViews

' __________________ _______ _________ _______ _________ _______ _ ______ ' |\ /|\__ __/\__ __/( ____ \|\ /

Thanh Pham 446 Nov 24, 2022
Animated UITextField enhance UX for the user by giving clarity that they are focused

JDCircularProgress JDTextField is animateable UITextField that can significantly enhance your user's experiences and set your app apart from the rest

Jawad Ali 22 Nov 17, 2022
This project will add a done button on your UITextField and UITextView

This project will add a done button on your UITextField and UITextView

Botla Venkatesh 0 Nov 23, 2021
UITextField category that adds shake animation

UITextField category that adds a shake animation like the password field of the OsX login screen. Screenshot Setup with CocoaPods pod 'UITextField+Sha

Andrea Mazzini 749 Dec 13, 2022
UITextField extension in Swift that adds shake animation

UITextField-Shake-Swift UITextField extension in Swift that adds shake animation Initially created by Andrea Mazzini (using Objective-C) on 08/02/14:

null 15 Jul 20, 2021
UITextField with underline and left image

TJTextField UITextField with underline and left image Version: 1.0 Features Add image in UITextField Left text pedding Underline whole UITextField Sho

Tejas Ardeshna 44 May 16, 2022
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
UITextField that automatically formats text to display in the currency format

CurrencyTextField The numbers that the user enters in the field are automatically formatted to display in the dollar amount format. For example, if th

Richa Deshmukh 49 Sep 28, 2022
UITextField that support currency in the right way.

PLCurrencyTextField Summary PLCurrencyTextField provides simple and user friendly support for the amount in the currency. Usage To start using the com

Łukasz Śliwiński 96 Nov 14, 2022
Animated UITextField and UITextView replacement for iOS

AnimatedTextInput iOS custom text input component used in the Jobandtalent app. Installation Use cocoapods to install this custom control in your proj

jobandtalent 757 Dec 15, 2022