GithubHelp home page GithubHelp logo

mlpautocompletetextfield's Introduction

MLPAutoCompleteTextField

"We believe that every tap a user makes drains a tiny bit of their energy and patience. Typing is one of the biggest expenditures of both. What we needed was a textfield that could be completed in as few keystrokes as possible even for very long words. Thus MLPAutoCompleteTextField was born."

Alt text|Alt text

About

MLPAutoCompleteTextField is a subclass of UITextField that behaves like a typical UITextField with one notable exception: it manages a drop down table of autocomplete suggestions that update as the user types. Its behavior may remind you of Google's autocomplete search feature. As of version 1.3 there is also support for showing the autocomplete table as an accessory view of the keyboard.

From version 1.5 and above MLPAutoCompleteTextField is compatible with iOS 5.0 or greater.

####Example:

A user is required to enter a long and complicated chemical name into a textfield. With an autocomplete textfield, chemical names that closely match her entered string can be displayed as she types, and if she sees the chemical name she was thinking of she can select it and have it entered into the textfield automatically. This reduces the amount of typing she has to do and helps prevent errors. All this can occur within a single view and without the need for a search tableview controller.

Usage

The goal for MLPAutoCompleteTextField is to create an autocomplete textfield that is quick and easy to use, yet eminently customizable. To get a working MLPAutoCompleteTextField instance, ensure you have done the following:

  1. Add the MLPAutoCompleteTextField, NSString+Levenshtein, MLPAutoCompletionObject.h, MLPAutoCompleteDataSource and MLPAutoCompleteTextFieldDelegate files into your project (should have seven files in total).

  2. Have an MLPAutoCompleteTextField instance allocated and initialized within some view.

  3. Set the textfield's "autoCompleteDataSource" property to a valid object that implements the required methods of the MLPAutoCompleteTextFieldDataSource protocol. Note that the method "autoCompleteTextField:possibleCompletionsForString:" is the method you use to return possible completions for the textfield's currently entered string. This method is expected to return either an array of NSString, or an array of objects conforming to the MLPAutoCompletionObject protocol, or a mix of both. This method is also called asynchronously.

  4. (Optional) Set the textfield's "autoCompleteDelegate" property to a valid object that implements the methods of the MLPAutoCompleteTextFieldDelegate protocol for further customization options.

You should now have a working MLPAutoCompleteTextField at this point.

Autocomplete as a Keyboard Input Accessory

As of version 1.3 of MLPAutoCompleteTextField, the autocomplete suggestions can be shown as a tableview that appears above the keyboard. To activate this feature, set the autoCompleteTableAppearsAsKeyboardAccessory property of the MLPAutoCompleteTextField instance to TRUE.

Notes

Traditionally, you might have seen something similar to the MLPAutoCompleteTextField implemented with something like a "search tableview controller". This approach has some limitations and boilerplate code which MLPAutoCompleteTextField has strived to overcome. An MLPAutoCompleteTextField is not meant to be a replacement for a search function, it is designed purely for quick string completion purposes.

The MLPAutoCompleteTextField sorting of autocomplete strings is powered by the NSString+Levenshtein category extension written by Mark Aufflick (based loosely on a Levenshtein algorithm written by Rick Bourner). This algorithm basically calculates the edit distance between two strings (the number of changes required to turn one string into the other).

When a datasource passes an array of strings to an MLPAutoCompleteTextField, the textfield sorts the strings according to edit distance and displays this list of autocomplete suggestions.

Used responsibly, we hope the MLPAutoCompleteTextField will open up new design possibilities for developers of all origins and skill levels.

:D

Performance

MLPAutoCompleteTextField uses a multi-threaded approach to it's sorting of autocomplete strings so that the main thread is never blocked and the UI stays 100% responsive.

Keep in mind that although you can pass an ungodly amount of strings in an array to the MLPAutoCompleteTextField at once, sorting performance will suffer directly related to the number of strings you give (we're talking on the magnitude of thousands of strings). If performance is suffering, you should find ways to reduce the amount of strings you pass to the MLPAutoCompleteTextField when it asks you for them. (For example, if you assume a user will always know the first letter of a word correctly, you may choose to only send an array of words that start with that letter or even close to that letter on the keyboard, rather than every single possible word you have).

Known Issues

  • Clear Color or Translucent textfields are a bit ugly at the moment.
  • Hide your autocomplete tableview (if its open) before rotating the view it's in, and then unhide after the rotation is done.

What to Expect in Future Updates

  • iOS 7 Styling: This class will be updated to match the design language of iOS 7 in iOS 7 apps.

  • Horizontal Scrolling Suggestions: There will be an option to display autocomplete terms in a slim, horizontally scrollable list above the keyboard, like the autocomplete on many Android devices.

  • Weighted Suggestions: In some cases, there may exist multiple autocomplete strings that are all equally possible completions for the current entered incomplete string. In current versions, the user will simply have to keep typing a few more characters to further narrow down the autocomplete suggestions to float the most probable string to the top of the autocomplete list.

    However, in the future you can expect to see a sort of "weighting" or "ranking" system, which will allow you to favor some strings over others by assigning a number to them. Strings with higher weight will appear closer to the top of the list of autocomplete suggestions. So even though a group of strings are all equally possible completions for a given incomplete string, the ones with higher weight are deemed as being the "more probable" matches and will be sorted accordingly.

    This should further reduce the number of characters a user has to type.

  • String Hiding: If an autocomplete suggestion is of such poor quality that it has nothing in common at all with the user's currently entered string, then there may be a built in option to not display this suggestion at all.

  • Tokenized Bolding: If a user has entered a string such as "Grate White Sha", and there is an autocomplete suggestion called "Great White Shark", then in the suggestion the word "Great" should be in bold, the word "White" should be regular, and the work "Shark" should have the "rk" bolded. This behaves more like Google's autocomplete. (A user can choose the reverse behavior too).

  • Background Dimming: When an autocomplete tableview menu is open, there should be an option to have the superview background dim a bit to keep the focus on the textfield and autocomplete suggestions.

License

MLPAutoCompleteTextField uses the MIT License:

Copyright (c) 2013, Mainloop LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

The NSString+Levenshtein category uses this license as stated in the .h and .m files:

NSString+Levenshtein

Copyright (c) 2009, Mark Aufflick All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of the Mark Aufflick nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY MARK AUFFLICK ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MARK AUFFLICK BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Credits

MLPAutoCompleteTextField was written by Eddy Borja, at Mainloop LLC.

NSString+Levenshtein category extension was written by Mark Aufflick.

If you make use of MLPAutoCompleteTextField, tell us about it! Feel free to leave comments, likes, hatemail, etc at [email protected]

These days I'm unable to continue working on this project due to other obligations, but I'm always open to pull requests.

More Stuff

Be sure to check out these other libraries:

MLPSpotlight
UIColor+MLPFlatColors
MLPAccessoryBadge
EBPhotoPages Gallery

mlpautocompletetextfield's People

Contributors

bimusiek avatar csknns avatar dzamataev avatar eddyborja avatar funnel20 avatar gbarcena avatar gioy avatar kurtzmarc avatar mikumi avatar mosamer avatar nessup avatar nonouf avatar odnairy avatar pahnev avatar sdsykes avatar trik avatar yas375 avatar yimingtang avatar zebtin 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mlpautocompletetextfield's Issues

Suggestions z-index problem when in static UITableView cell

For the app I'm working on, there is a form with some textfields. The autocomplete works without a problem inside a regular view in a view controller, but there are some z-index issues when the autocomplete textfield is inside a static cell of a UITableView.

It's hard to show with screenshots, but you can see the form below with the autocomplete suggestions showing up. When you try and click on one it dismisses the dialog and selects the MRN field below the suggestions.

ios simulator screen shot 2013-05-30 1 04 29 pm

Result tableView appears transparent

The result tableView appears transparent always, I tried to set the property autoCompleteTableBackgroundColor but nothing happens still transparent

AutoCompleteTableView positioning

Hi,
I'm trying to move down the autocomplete table view, since it appears in the middle of the AutoCompleteTextfield and covers half of the text. Is there any property or method to achieve this ?
I tried with autoCompleteTableOriginOffset/setAutoCompleteTableOriginOffset (in both viewWillAppear and viewDidLoad), but nothing moves or changes.

I'm using XCode Version 5.1.1 (5B1008), iOS 7.1.1 with storyboard.

Thanks

Using UITextFieldDelegate

I need to set my autocomplete field to also use a UITextField delegate, however doing so I get the following:

Obj-C -[MLPAutoCompleteTextField title]: unrecognized selector sent to instance 0x17647d70

Love this component by the way, works great otherwise.

tapping on textfield empty table appear.

can you add the option to appear a empty table while its being load from the web service. or else we cant find whether the function is working or not.

in other words there should be activity indicator until the data is fetched from the server to app.

View hierarchy issue when displaying autoCompleteTableView

Hello,

I really appreciate your work on MLPAutoCompleteTextField. I would like to use it in our project, because it fits our requirements perfectly. But I am now facing an issue when the autoCompleteTableView is displayed. I am currently using v1.5 added to project via Pods.

Here is my situation:
I have to generate a mask view dynamically from out a mask model that I retrieve by a web service. The mask model contains various objects. I made a screenshot to make things easier. ;)

  • Mask contains x groups (alternating cyan / blue color)
  • Group contains x column (alternating yellow / orange color)
  • Column contains x entries (alternating light / dark gray color)
  • Entries contains a label (green color) and an inputField (white color)

autocompleteissue

Now I subclassed UIView a few times (Mask, Group, Column, Entry) and generate the view when receiving the maskModel from the server. In my testcase I used the MLPAutoCompleteField as inputField in every entry. Now here is my issue:

When I type into an inputField the tableView will be displayed. But as you can see it is overlayed by the next group view. I had set clipsToBounds and masksToBounds to NO in every view in the hierarchy. But it seems to have no effect. I inspected your code an found a possible issue. The tableView will be inserted as subview into the superview of the inputField (in my case it's the MaskEntry - grey color).

While browsing GitHub I found out, that you fixed an similar issue by adding the tableView to the root view. So I replaced my version by the current state. But that the table view is completely misplaced and won't be diplayed under the input field.

Is there anything I am doing wrong? Any solutions?

I would really appreciate some help!

Best regards,
SlimShady0208

Can't find asciiLevenshteinDistanceWithString

I use cocoapod and added all your files per instruction.
Yet when I run the app I get Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString asciiLevenshteinDistanceWithString:]: unrecognized selector sent to instance 0x9d5bb40'

Any idea?

remove autocompleteString from custom UITableViewCell

Hi,

I'm trying to figure out a way to remove the autocompleteString from a custom UITableViewCell.

In the viewController:viewDidLoad I registered the custom UITableViewCell class & Nib with

registerAutoCompleteCellClass:forCellReuseIdentifier:
registerAutoCompleteCellNib:bundle:forCellReuseIdentifier:

then, in the delegate method

(BOOL)autoCompleteTextField:(MLPAutoCompleteTextField *)textField shouldConfigureCell:(UITableViewCell *)cell withAutoCompleteString:(NSString *)autocompleteString withAttributedString:(NSAttributedString *)boldedString forAutoCompleteObject:(id<MLPAutoCompletionObject>)autocompleteObject forRowAtIndexPath:(NSIndexPath *)indexPath

I tried to remove the autocompleteString from the custom cell

autocompleteString = nil; boldedString = nil; cell.textLabel.text = nil;

Unfortunately though, the autocompleteString keep showing inside the custom cell.
How to remove it ?

Thanks.

Can't click sugestion when using the control as a navigation top bar item

My issue is this, i can't touch the suggestion table view cells outside the frame of the navigation bar view, i try to alter the code in the library but the results are the same, i see the reports about the control fixed in some other issues like using the control in a tableview, the problem here is similar because the control is inside a navigation bar item using storyboard, i think is because the view of the tableview is taking all the touch events apart of the touch events inside the navigation top bar frames.

What can i do to fix this issue, i can bring more information of the proyect if you want. Thanks for this amazing library. Sorry for my bad english.

trytofixissue

2 Xcode Compiler warnings for unused variables

When I Archive my project, Xcode 5.1.1 shows 2 compiler warnings for unused variables.
There are several ways to solve this, see for example:
http://stackoverflow.com/questions/5451123/how-can-i-get-rid-of-an-unused-variable-warning-in-xcode

I have chosen to use:

__unused
  1. MLPAutoCompleteTextField/MLPAutoCompleteTextField.m:600:10: Unused variable 'classSettingSupported'

  2. MLPAutoCompleteTextField/MLPAutoCompleteTextField.m:919:23: Unused variable 'firstObject'

AutoCompleteSource protocol

From the readme, I implemented autoCompleteTextField method, but I still get the following error message.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An autocomplete datasource must implement either autoCompleteTextField:possibleCompletionsForString: or autoCompleteTextField:possibleCompletionsForString:completionHandler:'

AutoCompleteDataSource.h

#import "MLPAutoCompleteTextFieldDataSource.h"

@interface StationAutoCompleteSource : NSObject <MLPAutoCompleteTextFieldDataSource>

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
 possibleCompletionsForString:(NSString *)string
            completionHandler:(void(^)(NSArray *suggestions))handler;

@property (strong, nonatomic) NSArray *allCountries;
@property (strong, nonatomic) NSArray *countryObjects;
@property (assign) BOOL testWithAutoCompleteObjectsInsteadOfStrings;

@end

AutoCompleteDataSource.m

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
possibleCompletionsForString:(NSString *)string
completionHandler:(void (^)(NSArray *))handler
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        NSArray *completions;
        completions = [self allCountries];
        handler(completions);
    });
}

Crash on iOS 5.1 due to lack of attributed text support on UILabel before iOS 6

The code checks for this case then asserts. Therefore MLPAutoCompleteTextField crashes on iOS versions less than 6. The README states it supports iOS 5.0+

lines 249-250 of MLPAutoCompleteTextField.m (as of commit 0443f02):

    BOOL attributedTextSupport = [cell.textLabel respondsToSelector:@selector(setAttributedText:)];
    NSAssert(attributedTextSupport, @"Attributed strings on UILabels are  not supported before iOS 6.0");

Tableview Keyboard Input Accessory not shown when using auto layout and storyboard

Hi,

I'm trying to get the tableview keyboard input accessory running but somehow can't get it working. After a bit of debugging I found out it's related the storyboard and using autolayout. When I disable auto layout the tableview is shown. When I enable autolayout the frame of the tableview is set to 0,0,0,0 I guess because the MLPAutoCompleteTextField has no dimensions yet. Hope you know how to fix this.

Thanks!
Bart

Scroll Table

Hello all!
I want to scroll table view with autocomplete to top, after user typer in text field. It's possible with this component?

Autocomplete Table does not rearrange on orientation change

I am using the autocomplete on iPad, and my app supports any orientation. The autocomplete table is able to show up correctly in any orientation, but when it is already open and I rotate the device, the table does not follow the frame changes to match the new position of the text field.

Can i have the selected unique id ?

I have a NSMutablearray with NSDictionary objects and keys, for example: countryId and countryName. How can I get the countryId of selected row?

How to reload this?

Let's say I have a service that fetches auto complete suggestions. I have to reload the data to show the web service response. Any ideas?

App get Stuck in iOS 7

I have used this library in my current project, but I dnt know what is the reason but this make the Device stuck even with opened keyboard too.

in Stack trace, I found it always raise this issue when i try too type and crashes at
dispatch_semaphore_wait(sentinelSemaphore, DISPATCH_TIME_FOREVER);
from -main method of MLPAutocompleteTextField.m

Very surprising part it that When i try to type something from Keyboard attached to machine then its not crashing but when i use the On screen keyboard of simulator It crashes everytime.

how to know if the table is showing?

Sorry, I might be missing something very obvious, but is there a way to tell if the tableview is currently expanded?

I tried subclassing and putting a setter on autoCompleteTableViewHidden but that's not it.

I need to change my layout whenever the table is open.

Thanks in advance!

TableView height should be adjustable

By default, the table height fits about 2.5 results. This value should be adjustable so one could take advantage of all space available, if desired.
Also, when the results are show as keyboard accessory, the heigh does not decrease when there are less autocomplete suggestions available (ie only one).
Moreover, I noticed that using the keyboard accessory, when there's no suggestions, there's still an invisible table or view on top of the keyboard, so I cannot tap the superview to dismiss the keyboard. This does not happen with the dropdown.

autoCompleteDelegate used in the initialiser but is not yet set

The IBOutlet autoCompleteDelegate is accessed from the initializer (init-> initialize-> styleAutoCompleteTableForBorderStyle:), but the outlets are not set while the designated initializer chain is called, so delegate method autoCompleteTextField:shouldStyleAutoCompleteTableView:forBorderStyle: will never get called while the class is initializing

I created a pull request #73 that should fix this issue.

Auto Suggestion based on user input

Is it possible to auto suggest item based on user input. fx. I have the following url "https://itunes.apple.com/search?term=" where users have to enter a search term?

I have tried to the following:

define baseURL @"https://itunes.apple.com/search?term="

  • (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
    possibleCompletionsForString:(NSString *)string
    completionHandler:(void (^)(NSArray *))handler
    {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
    if(self.simulateLatency){
    CGFloat seconds = arc4random_uniform(4)+arc4random_uniform(4); //normal distribution
    NSLog(@"sleeping fetch of completions for %f", seconds);
    sleep(seconds);
    }

    NSMutableArray* jsonObject = [[NSMutableArray alloc]init];
    NSMutableArray* suggestionlist = [[NSMutableArray alloc]init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",baseURL,textField.text]]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSError* error;
    jsonObject = [NSJSONSerialization
                  JSONObjectWithData:response
                  options:0
                  error:&error];
    
    for (int i = 0 ; i < jsonObject.count; i++) {
        NSString* artistName = [[jsonObject objectAtIndex:i] objectForKey:@"artistId"];
        [suggestionlist addObject:artistName];
    }
    

    handler(suggestionlist);
    });
    }

But I got the following error:

GAIUncaughtExceptionHandler(NSException ) (GAIUncaughtExceptionHandler.m:41): Uncaught exception: data parameter is nil
2014-05-15 11:49:54.224 MLPAutoCompleteDemo[6349:5503] GoogleAnalytics 2.0b4 void GAIUncaughtExceptionHandler(NSException *) (GAIUncaughtExceptionHandler.m:38): Bailing on multiple uncaught exceptions: data parameter is nil
2014-05-15 11:49:54.224 MLPAutoCompleteDemo[6349:5503] *
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

Any suggestions why it is not working?

Crash when typing too fast

I'm testing on an iPad 1 running iOS 5.1. There is a concurrency problem where a crash occurs in MLPAutoCompleteFetchOperation because sentinelSemaphore is signalled in -[MLPAutoCompleteFetchOperation cancel] while it is nil because it has never been created.

If a MLPAutoCompleteTextFieldDelegate doesn't implement autoCompleteTextField:possibleCompletionsForString:completionHandler: then the semaphore will never be created in -[MLPAutoCompleteFetchOperation main]. Therefore if the user is typing fast enough that fetchAutoCompleteSuggestions gets called a second time while there is an operation on the queue, it will get cancelled which will call the operation's cancel method which attempts to signal the semaphore which was never created.

I suggest putting a guard to make sure the semaphore isn't nil in the -[MLPAutoCompleteFetchOperation cancel] method like so:

- (void) cancel
{
    if (sentinelSemaphore) dispatch_semaphore_signal(sentinelSemaphore);
    [super cancel];
}

Adding MLPAutoCompleteTextField to a view programitacally

Hi,
First of all thanks for a great plugin.
I'm using the example project and I've been trying to add the MLPAutoCompleteTextField to the MLPViewController programatically.
I've deleted the view.xib file, but I cannot seem to get the custom text field to appear in the view programatically. Could you please advise how I can achieve this. I've included my viewDidLoad implementation below.
Thanks again,
Patrick

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.autocompleteTextField = [[MLPAutoCompleteTextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
    self.autocompleteTextField.delegate = self;
    self.autocompleteTextField.autoCompleteDataSource = self;
    self.autocompleteTextField.autoCompleteDelegate = self;


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowWithNotification:) name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideWithNotification:) name:UIKeyboardDidHideNotification object:nil];

    //Supported Styles:
    //[self.autocompleteTextField setBorderStyle:UITextBorderStyleBezel];
    //TODO[self.autocompleteTextField setBorderStyle:UITextBorderStyleLine];
    //[self.autocompleteTextField setBorderStyle:UITextBorderStyleNone];
    [self.autocompleteTextField setBorderStyle:UITextBorderStyleRoundedRect];


    //You can use custom TableViewCell classes and nibs in the autocomplete tableview if you wish.
    [self.autocompleteTextField registerAutoCompleteCellClass:[MLPCustomAutoCompleteCell class]
                                       forCellReuseIdentifier:@"CustomCellId"];

    [self.view addSubview:self.autocompleteTextField];


}

Unable to show self.autoCompleteTableView on the popover view in iPad in XCode 6 development

I'm using your github project for my developments. Thanks for this. This is very simple to use and I did some changes according to our requirements.

Earlier I used this in xcode 5.1 development and now i converted this into xcode 6.1 (Objective C). But when i run the same application in ios 7 and 8 in iPad by using xcode 6, self.autoCompleteTableView is not showing the top view. It shows in the bottom view.

It was working well in xcode 5.1 build.

XCode 5.1 build

xcode5

XCode 6.1 build

xcode6
I want to show this as XCode 5.1 build.

Below is my code.

-(void)expandDropDownAutoCompleteTableForNumberOfRows:(NSInteger)numberOfRows
{
[self resetDropDownAutoCompleteTableFrameForNumberOfRows:numberOfRows];
if(numberOfRows && (self.autoCompleteTableViewHidden == NO)){
[self.autoCompleteTableView setAlpha:1];

    if(!self.autoCompleteTableView.superview){
        if([self.autoCompleteDelegate
            respondsToSelector:@selector(autoCompleteTextField:willShowAutoCompleteTableView:)]){
            [self.autoCompleteDelegate autoCompleteTextField:self
                               willShowAutoCompleteTableView:self.autoCompleteTableView];
        }
    }

    [self.superview bringSubviewToFront:self];

    UIView *rootView;
    if (gaiDevice == iPad)
    {
        rootView = [UIApplication sharedApplication].keyWindow;
        [rootView insertSubview:self.autoCompleteTableView aboveSubview:[UIApplication sharedApplication].keyWindow.rootViewController.view];

    }
    else
    {
        [rootView insertSubview:self.autoCompleteTableView
                   belowSubview:self];

        rootView = [self.window.subviews objectAtIndex:0];
        [rootView insertSubview:self.autoCompleteTableView
                   belowSubview:self];
    }

    [self.autoCompleteTableView setUserInteractionEnabled:YES];
    if(self.showTextFieldDropShadowWhenAutoCompleteTableIsOpen){
        [self.layer setShadowColor:[[UIColor blackColor] CGColor]];
        [self.layer setShadowOffset:CGSizeMake(0, 1)];
        [self.layer setShadowOpacity:0.35];
    }
} else {
    [self closeAutoCompleteTableView];
    [self restoreOriginalShadowProperties];
    [self.autoCompleteTableView.layer setShadowOpacity:0.0];
}

}

So how can I show this in iPad's top view on the popover in xcode 6 build??

Thank you!

Not working on my app.

I'm studying iOS programming and I am implementing MLPAutoCompleteTextField to my simple app. I followed instructions and also referred to the sample project. But when I build & run my project, it is successfully compiled but the suggestions are not displayed.
Here's how it looks:http://d.pr/i/Uv3D

AddQuoteViewController.h

#import <UIKit/UIKit.h>
#import "MLPAutoCompleteTextFieldDataSource.h"
#import "MLPAutoCompleteTextFieldDelegate.h"

@class MLPAutoCompleteTextField;
@interface AddQuoteViewController : UIViewController <UITextFieldDelegate, MLPAutoCompleteTextFieldDataSource, MLPAutoCompleteTextFieldDelegate>

@property (strong, nonatomic) IBOutlet MLPAutoCompleteTextField *authorTextField;
- (IBAction)saveQuoteButton:(id)sender;
@end

AddQuoteViewController.m

#import "AddQuoteViewController.h"
#import "MLPAutoCompleteTextField.h"
#import "AuthorAutoSuggestTableViewCell.h"
#import <QuartzCore/QuartzCore.h>

@implementation AddQuoteViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowWithNotification:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideWithNotification:) name:UIKeyboardDidHideNotification object:nil];

    [self.authorTextField setBorderStyle:UITextBorderStyleRoundedRect];
}

- (void)keyboardDidShowWithNotification:(NSNotification *)aNotification {
    [self.author setAlpha:0];
}

- (void)keyboardDidHideWithNotification:(NSNotification *)aNotification {
    [self.author setAlpha:1];
    [self.authorTextField setAutoCompleteTableViewHidden:NO];
}

- (NSArray *)possibleAutoCompleteSuggestionsForString:(NSString *)string {
    NSArray *sample = @[@"Ape", @"Bird", @"Cat", @"Dog"];
    return sample;
}

- (BOOL)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
          shouldConfigureCell:(UITableViewCell *)cell
       withAutoCompleteString:(NSString *)autocompleteString
         withAttributedString:(NSAttributedString *)boldedString
            forRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return YES;
}

autoCompleteTableView shadow is not effected ?

hi Eddy,
i've applied these lines of code :
self.autoCompleteTableView.layer.masksToBounds=NO;
self.autoCompleteTableView.layer.shadowOffset=CGSizeMake(1,1);
self.autoCompleteTableView.layer.shadowRadius=5.0f;
self.autoCompleteTableView.layer.shadowOpacity=1;
self.autoCompleteTableView.layer.shadowColor=[UIColor orangeColor].CGColor;

in the method -setNoneStyleForAutoCompleteTableView
but,i couldn't see them on the tableview.

Styling the autocomplete table view

Is there any easy way to style the autocomplete table view positioning, border color/width/radius, text color/positioning etc. or do I have to tamper with the source code?

For example the text in the autocomplete table view is black in the example project but in my project it's light blue, and has a border that also is light blue.

So this is just a question on styling the appearance of the autocomplete table view and not really an issue, but I didn't know where else to ask.

iOS 8 (simulator): autoCompleteTableView doesn't appear

Trying to switch from iOS 7.1 to iOS 8, I noticed that the autoCompleteTableView doesn't appear anymore. I double checked that data is fetched correctly, so it should be something related to the tableview's visibility.
Instead of the tableview, only a bottom shadow appears.

Before typing
screen shot 2014-09-20 at 16 24 18

After typing
screen shot 2014-09-20 at 16 24 44

I'm on OSX 10.9.5 (Mavericks), using XCode 6.0.1 (6A317)
My app is written with Objective-C, no swift at all.

Cannot connect the autoCompleteDataSource to the IBOutlet

I am fairly new to IOS, and am sure I am missing something. I am unable to connect the autoCompleteDataSource to my IBOutlet in my view, but I can manually connect it by calling setAutoCompleteDataSource. Relevant code is below.

GBProductAutocomplete.h

#import <Foundation/Foundation.h>
#import "MLPAutoCompleteTextFieldDataSource.h"

@interface GBProductAutocomplete : NSObject <MLPAutoCompleteTextFieldDataSource>

@end

GBProductAutocomplete.m

#import "GBProductAutocomplete.h"

@implementation GBProductAutocomplete

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
 possibleCompletionsForString:(NSString *)string
            completionHandler:(void (^)(NSArray *))handler
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        NSArray *completions;
        completions = [NSArray arrayWithObjects:@"hello", @"world", nil];

        handler(completions);
    });
}

@end

GBViewController.h

#import <UIKit/UIKit.h>
#import "MLPAutoCompleteTextFieldDelegate.h"

@class GBProductAutocomplete;
@interface GBManualAddViewController : UIViewController <UITextFieldDelegate, MLPAutoCompleteTextFieldDelegate>

@property (weak, nonatomic) IBOutlet MLPAutoCompleteTextField *autocompleteTextField;
@property (strong, nonatomic) IBOutlet GBProductAutocomplete *autocompleteDataSource;
@property (weak, nonatomic) IBOutlet MLPAutoCompleteTextField *textField;

@end

GBViewController.m

#import "GBManualAddViewController.h"
#import "MLPAutoCompleteTextField.h"
#import "GBProductAutocomplete.h"

@interface GBManualAddViewController ()

@end

@implementation GBManualAddViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self.textField setAutoCompleteDataSource:[[GBProductAutocomplete alloc] init]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
          shouldConfigureCell:(UITableViewCell *)cell
       withAutoCompleteString:(NSString *)autocompleteString
         withAttributedString:(NSAttributedString *)boldedString
        forAutoCompleteObject:(id<MLPAutoCompletionObject>)autocompleteObject
            forRowAtIndexPath:(NSIndexPath *)indexPath;
{
    //This is your chance to customize an autocomplete tableview cell before it appears in the autocomplete tableview
    NSString *filename = [autocompleteString stringByAppendingString:@".png"];
    filename = [filename stringByReplacingOccurrencesOfString:@" " withString:@"-"];
    filename = [filename stringByReplacingOccurrencesOfString:@"&" withString:@"and"];
    [cell.imageView setImage:[UIImage imageNamed:filename]];

    return YES;
}

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
  didSelectAutoCompleteString:(NSString *)selectedString
       withAutoCompleteObject:(id<MLPAutoCompletionObject>)selectedObject
            forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(selectedObject){
        NSLog(@"selected object from autocomplete menu %@ with string %@", selectedObject, [selectedObject autocompleteString]);
    } else {
        NSLog(@"selected string '%@' from autocomplete menu", selectedString);
    }
}

@end

If I uncomment the line [self.textField setAutoCompleteDataSource:[[GBProductAutocomplete alloc] init]]; in viewDidLoad the autocomplete will work, but I cannot figure out why I cannot drag from the outlet in the nib to connect the property.

TableView is clipped by super view

When the super view of the textField is small, the tableView is clipped. Is there is any way to add the table view as a subview to the window instead of its superview?, i tried to do that but the table view covered the half of the textField

can't click on suggestion

I implement simple datasource for autocomplete list and show suggestions, but when i try to select one of the suggestion it do nothing.

I also try to implement some delegate methods like:

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
  didSelectAutoCompleteString:(NSString *)selectedString
       withAutoCompleteObject:(id<MLPAutoCompletionObject>)selectedObject
            forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"select: %@", selectedString);
}

Nothing happens.

http://s1.ipicture.ru/uploads/20131008/At8TrUtS.png

Memory leak of semaphore in iOS 5

On iOS 5 which doesn't use ARC, dispatch objects such as semaphores must be explicitly released. In MLPAutoCompleteFetchOperation sentinelSemaphore is created but never released. The semaphore will leak because without ARC, you need to call dispatch_release() when you're done with it. (see https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html#//apple_ref/doc/uid/TP40008079-CH1-SW2)

which says:

Dispatch Queues and Automatic Reference Counting

The behavior of dispatch queues in an automatic reference counting environment varies depending on the deployment target that you choose for a given build target.

  • iOS 6 and later—Dispatch objects (including queues) are Objective-C objects, and are retained and released automatically.
  • OS X 10.8 and later—Dispatch objects (including queues) are Objective-C objects, and are retained and released automatically.
  • Earlier versions—Dispatch objects are custom objects. You must handle the reference counting manually by calling dispatch_retain and dispatch_release.

If you need to use manual reference counting in an ARC-enabled app with a later deployment target (for maintaining compatibility with existing code), you can disable Objective-C-based dispatch objects by adding -DOS_OBJECT_USE_OBJC=0 to your compiler flags.

AutoComplete as keyboard accessory bug

Autocomplete tableview without any rows still appears on screen with alpha=0. That's prevents views laying under this tableview catching any touches.

blank font on iPhone 5

Just in iPhone 5, I have some fields not showed, it's there... but i can't see. Doesn't happen in simulator, only in iPhone 5. Does anyone knows why?

3 Xcode Compiler warnings for 64-bit architecture

When I compile in Xcode 5.1.1 for a 64-bit Simulator, I get 3 warnings.
I have added them here, incl. a proposed fix. I hope you can effectuate these changes.

  1. MLPAutoCompleteTextField/NSString+Levenshtein.m:87:13: Implicit conversion loses integer precision: 'NSUInteger' (aka 'unsigned long') to 'int'

Proposed solution:

NSUInteger n = [dataA length];
  1. MLPAutoCompleteTextField/NSString+Levenshtein.m:88:13: Implicit conversion loses integer precision: 'NSUInteger' (aka 'unsigned long') to 'int'

Proposed solution:

NSUInteger m = [dataB length];
  1. MLPAutoCompleteTextField/MLPAutoCompleteTextField.m:239:50: Values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead

Proposed solution:

return [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.section,(long)indexPath.row];

Features enhancement.

Hi Eddy,

First I wanted to say congrats about the great work with MLPAutoCompleteTextField. I started playing with it recently. So here are my goals:

a) I want to search on a large array of strings. I experimented with 10K and it is not bad (~1sec). Do you have any ideas how to optimize for larger arrays? Perhaps some caching?
b) I have already pre-sorted the array. Does it helps? I cannot seem to find in your code if it sorts the array or not.
c) How can I change your code so that the search takes place on multiple words?I want to do this because my array contains entries with multiple words. Basically what I want to achieve is this: the user types in one word, the word is matched as it does now, but then when the user types in a second word, then the second word is tried to be matched with the results of the first word. Could you point me to your code?
d) Finally you mention that you want to do have some ranking in the array of strings. How could I modify your code to address this?

Once again thank you for your help. Great work!

-Alex

Storyboard demo

Could you please add a demo using storyboard.
I have problems figuring out how to connect textfields to datasources, and since I am using storyboards I think that a sample would help.

Thanks

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.