Code Monkey home page Code Monkey logo

searchtextfield's Introduction

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.

searchtextfield's People

Contributors

albeva avatar apasccon avatar artem-kalmykov avatar bryant1410 avatar chrismhinsch avatar daisyramos317 avatar juliencampy avatar kiril avatar langford avatar mattstanford avatar resand avatar rivera-ernesto avatar thibauddavid avatar xhotsniperx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

searchtextfield's Issues

Adjusting the width?

Is there a way to adjust the auto-complete suggestion list? I tried setting the size when I create the object with CGRect but it didn't work.

[feature request] Adding a delimiter character

It would be great to be able to make the list only activate when a certain character is typed, say the "@" character. I realize this is a bit of a deviation from the original goal of the code.

Custom Search Result Cell?

Your library is exactly what I need, however, is there a way to specify a custom table cell to be used as a search result? I want to customize the UI of the result a bit more than what is standard (more than just title, subtitle, image, etc.)

[Feature Request] Carthage Support

It would be nice to import this as a framework with Carthage, because this is a good, regularly updated project and not everyone is using CocoaPods or likes manually integrating it.

Suggestions Appear below the keyboard? ... and adjustment of the view due to keyboardWill Show is reset

first of all I thank you for that library it is a must have one. However, I have two issues with the library and they are as follows:
1st:
the suggestions table appear below the keyboard... but since the text field is nearly in the lower middle I prefer to show the table above the textField
2nd:
since I want the user to see the contents while typing I shift the textField view upwards... and it remains there until a choice from the suggestions table is Made.. the shifted view is reset to its original place behind the keyboard
3rd:
I know I only said 2, but can I have the option to resize the suggestion table width (not by resizing the textField itself)

One Last Comment: in the inline Mode: How can I accept the text without writing all of it

Manually add file, syntax errors

Hi,

Has anyone by any chance , had seen errors for the SearchTextField.swift errors.
When i drag to project, it gives me syntax errors of the file. ANy help would be really appreciated.

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.

right to left support

I want the list of countries to appear from right to left.
How would /i go about to do that?

thanks

Get the filtered results

Is there a way to get filtered results?
In the itemSelectionHandler, I get position and item. But the position is as per the filtered list & not the original list. Here filtered list means the list which is formed after the user enters a character on the textfield and original list means the list of items supplied to the textfield for filtering.

Please help with the above issue.

Suggestion: when startVisible=true, show full list if user clears the field

I have been playing with your code, which works fantastic by the way.

I really want my users to choose from a list, but I want them to be able to override if they really need to, and filter quickly. So, I load up a large list of options and use startVisible=true and all is grand.

However, if they type a few things and then erase back to blank, your current implementation does not reload the list.

Just needed to make 1 small change to make this work:

if text!.isEmpty {
            clearResults()
            tableView?.reloadData()
            self.placeholderLabel?.text = ""
        }

Change to:

if text!.isEmpty {
            clearResults()
            tableView?.reloadData()
            filter(true)
            self.placeholderLabel?.text = ""
        }

I'm not sure if this creates other problems, but it seems to work for me!

Suggestions do not show up in Simulator

Inline suggestions work fine, but the dropdown does not work in the simulator.
Attached is a screenshot of the example app running on Simulator (iPhone 6 iOS 10.3)

simulator screen shot jul 28 2017 11 25 10 am

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

[Feature] highlight all occurrence in result list

Hi,

do you know if it's possible to add highlight (set pattern search bold in result list) on all occurrence of the pattern in each line string ?

example :

  • user search for 'es'
  • in list we have : 'test', 'test test'
  • Each 'es' are highlighted

Regards,

S0r4

Suggestions not showing at all!

I downloaded the example project, and the country and acronym suggestions are not showing at all.
Only the inline suggestions are working. Maybe you messed the working part when you added the inline feature
Your project is really cool, I would really like to use it, so if you could please look into it.
Thanks in advance

Hide keyboard but show list

Hello guys and thanks for your work...

I need to doesn't´t show the keyboard ontap, so only display the list... I try it delegating

extension X: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}

but doesn't works, just no appear nothing, no list (startvisible = true)

Any idea? Thanks!

Nothing get selected while using gesture recogniser ?

In View Controller :

viewDidLoad()
{
                    self.ClientList.itemSelectionHandler = {item in
                        let title = item.title
                        print("Title Name of List = "+title)
                        self.ClientList.text=title
                        self.view.endEditing(true)

                    }
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: 
Selector("dismissKeyboard")))
}

    func dismissKeyboard()
    {
        ClientList.resignFirstResponder()
        self.view.endEditing(true)

    }

Proposals disappearing right away (the second time searchTF is used)

The first time I use the searchTextField, the proposals are displayed nicely
simulator screen shot 6 mars 2017 a 18 04 39

But the second time I display the searchTF, the proposals appear, and then disappear right away before I have time to select an entry.
simulator screen shot 6 mars 2017 a 18 05 08

Maybe an issue with userStoppedTypingHandler ?
This didn't happen in release 1.0.4, then I upgraded to 1.0.9 and the issue appeared.

Thanks !

Hit Return Key when textfield is not empty will clear the content of the textfield

If I am typing with the tableview showing, the first filtered result will be chosen and put into the textfield if I hit return key. However, if I click the textfield again without typing and hit the return key. Since there are no filtered results, the following method will produce empty string and the existing content of the textfield will be cleared.

open func textFieldDidEndEditingOnExit() {
        self.text = filteredResults.first?.title
}

Multi Search in text

Hi,
actually this is a good component and it's very needed. good job. but when I used it in my application I used it to Seach in contact list and it's working fine as I mentioned in First image, BUT when I'm trying to Seach on another name it's not working as I mentioned in Second image. So can I use this to search in more one like in my application I'm trying to add users to to send mail to them so I need to add for ex 3 users. please advise and thanks for your support

first search
second search

SearchTextField becomeFirstResponder() does not work

Hi !
I have an issue with a SearchTextField.

My ViewController contains 2 IBOutlets:

  • a standard UITextField (mailTextField)
  • a SearchTextField (schoolTextField)

When I press return when editing the first textField, I want the SearchTextField to become the first responder.

Here is my code:

        
        if textField == mailTextField {
            
            guard (mailTextField.text?.isValidEmail) == true else {
                self.mailTextField.resignFirstResponder()
                displayAlert(title: "Erreur", message: "L'adresse e-mail saisie ne semble pas valide")
                return false
            }
            
            if school == nil {
                self.schoolTextField.becomeFirstResponder()
            } else {
                self.mailTextField.resignFirstResponder()
            }
            
        } else if textField == schoolTextField {
            self.schoolTextField.resignFirstResponder()
        }
        return true
    }

So, when self.schoolTextField.becomeFirstResponder() is called, this SearchTextField should become the first responder and begin editing.
I debugged and put a few prints. What happens is that the SearchTextField actually becomes the first responder (didBeginEditing is called), but then resignFirstResponder() is called on it (not by anything in my VC, I removed everything to make sure of that). And then didEndEditing is called on it.

In viewDidAppear, if I put self.schoolTextField.becomeFirstResponder(), it works perfectly ...
Also, if the SearchTextField is the first responder and then in textFieldShouldReturn, I put self.mailTextField.becomeFirstResponder(), it also works perfectly.

Apparently, the problem appears when having a standard UITextField as the first reponder and calling becomeFirstResponder() on the SearchTextField.

Thanks for your help.

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.
}

}

Results showing up under other controls

I have a TableView with multiple rows and when I have your control in one of the rows and the suggestions come up it displays under the other rows thus making it not viewable. Do you have any suggestions to fix this. I have tried to bring the subview to the front but that does not work and I also tried setting the zPosition of the control higher than others and it still seems to not work.

Simple search not working after 'pod install' in XCode 8

Simple search with the distro that came after Pod install does not work (Xcode 8.3.3 (8E3004b) :

...
Installing SearchTextField (1.1.4)

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

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

**

The only way I could make this work was by copying the class from the example project directly into my project, under Pods/SeachTextField.

I see that the latest version is 1.1.6, but 'pod install' downloads 1.1.4, not sure why.

change height of search TableView

Hi, is there a way to change the height of the search tableview? So that i can put it in a tableviewcell and it is contained by the cell height?

property placeholder textColor

How to change the placeholder property textColor of the placeholder if it is as fileprivate, this requires it to change the color of the field when I make field validations.

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.

FilterItems frame not changing when scrolling

I have put SearchTextField in a UIScrollVeiw. but the problem is when scroll view scrolling FilterItems frame not changing. it works when I reset text in scrollViewDidScroll.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
acronymTextField.text = acronymTextField.text // hack for move filter screen with textfield when scrolling
}

img_8495

results appearing if I set text on textfield

If I programmatically set the text on the text field, I am finding that the filtered list of matching results appear below the text field.

Is there a way to stop the list appearing when text is set programmatically?

ps love the control - and great work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.