Kishore Kumar
Kishore Kumar

Reputation: 4375

How to make textfield input view as search bar?

I have tried to get proper solution ,but I can't any programmers please give me a idea how to make.

1.is it possible to make uitextfield as uisearchbar?

 UISearchBar *search=[[UISearchBar alloc]init];
  search.delegate=self;
  [_txtLocation setInputView:search];

2.While user types the values I need show it as overlay at the bottom of the text field...

3.Please help me to find out the solution..

Upvotes: 2

Views: 4372

Answers (2)

Rumin
Rumin

Reputation: 3790

To make Text Field work like Search Bar implement - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string delegate method of UITextField. So basically, you need to implement AutoComplete feature and this how you do it. To detect which textfield is triggered use assign tag to the textfield.

In your ViewController.h file:

@interface ViewController :
 <UIViewController<UITextFieldDelegate,UITableViewDataSource, UITableViewDelegate>
{
    UITableView *autocompleteTableView;
    UITextField * searchtextField1;
    UITextField * searchtextField2;
    NSMutableArray *autoCompleteList;
    NSMutableArray *initalList;

}

In your ViewController.m file:

- (void)viewDidLoad {
searchtextField1 = [[UITextField alloc]
                              initWithFrame:CGRectMake(5,0, 245, 33)];

searchtextField2.tag = 2;
searchtextFeild1.tag = 1;   


    searchtextField.placeholder = @"eg: make up";

    searchtextField.textColor = [UIColor whiteColor];

    //[imageView addSubview:searchtextField];
    //[self.view addSubview:imageView];


    autoCompleteList = [[NSMutableArray alloc] init];
    searchtextField1.delegate = self;
    searchtextField2.delegate = self;

    autocompleteTableView = [[UITableView alloc]init];



    if(screenRect.size.height == 568)
    {
        float X_Co_tbl = (self.view.frame.size.width - 271)/2;
        [autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 105, 271, 120)];
    }

    else if (screenRect.size.width == 414)
    {
        float X_Co_tbl = (self.view.frame.size.width - 281)/2;
        [autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 145, 281, 120)];
    }
    else if(screenRect.size.width == 375)
    {
        float X_Co_tbl = (self.view.frame.size.width - 281)/2;
        [autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 125, 281, 120)];
    }
    else
    {
        float X_Co_tbl = (self.view.frame.size.width - 271)/2;
        [autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 95, 271, 120)];
    }
    autocompleteTableView.delegate = self;
    autocompleteTableView.dataSource = self;
    autocompleteTableView.scrollEnabled = YES;
    autocompleteTableView.hidden = YES;
    [self.view addSubview:autocompleteTableView];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    autocompleteTableView.hidden = YES;

    return YES;
}


- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
    autocompleteTableView.hidden = NO;
    if (textField.tag == 1) {
    /// Initialize your array for searchTextFeild1;
    initialList = [[NSMutableArray alloc]initWithObjects:@"Face wash",@"Morning face wash",@"Cleanser", nil];
}
if (textField.tag == 2) {
    /// Initialize your array for searchTextFeild2;
    initialList = [[NSMutableArray alloc]initWithObjects:@"Face wash",@"Morning face wash",@"Cleanser", nil];
}
    NSString *substring = [NSString stringWithString:textField.text];
    substring = [substring
                 stringByReplacingCharactersInRange:range withString:string];
    [self searchAutocompleteEntriesWithSubstring:substring];
    return YES;
}

/// You make Text Field work as Search Bar here
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {

    // Put anything that starts with this substring into the autocompleteUrls array
    // The items in this array is what will show up in the table view
    [autoCompleteList removeAllObjects];
    for(NSString *curString in initialList) {
        //NSRange substringRange = [curString rangeOfString:substring];

        if ([curString rangeOfString:substring options:NSCaseInsensitiveSearch].location != NSNotFound) {
            [autoCompleteList addObject:curString];
        }
    }
    [autocompleteTableView reloadData];
}

#pragma mark UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
    return autoCompleteList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = nil;
    static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
    }

    cell.textLabel.text = [autoCompleteList objectAtIndex:indexPath.row];
    return cell;
}

#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    searchtextField.text = selectedCell.textLabel.text;

    autocompleteTableView.hidden = YES;

    [self goPressed];

}

Upvotes: 1

vijay
vijay

Reputation: 165

In .h file

    #import <UIKit/UIKit.h>

    @interface SEMainVC : UIViewController <UITextFieldDelegate>{
        NSMutableArray *dummyArray;
        NSMutableArray *searchArray;
        NSString *searchTextString;
    }

    @property (weak, nonatomic) IBOutlet UITextField *searchTextField;
    @property (weak, nonatomic) IBOutlet UITableView *contentTableView;

    - (void) setupData;

    @end

In .m file

@interface SEMainVC ()

@end

@implementation SEMainVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    //set the selector to the text field in order to change its value when edited
    [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //here you set up the methods to search array and reloading the tableview
    [self setupData];
    [self updateSearchArray];
    [self.contentTableView reloadData];
}
//setting up the data sourch for the mutable array
- (void) setupData {
    dummyArray = [[NSMutableArray alloc] init];

    [dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dummy 1", @"name" , @"image1.JPG", @"image" , @"dummy 1 description textview", @"description", nil]];
    [dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dummy 2", @"name" , @"image1.JPG", @"image" , @"dummy 2 description textview", @"description", nil]];
    [dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dummy 3", @"name" , @"image1.JPG", @"image" , @"dummy 3 description textview", @"description", nil]];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [searchArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if( cell == nil ){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.textLabel.text = [[searchArray objectAtIndex:indexPath.row] objectForKey:@"name"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"DummyDetail" sender:[NSNumber numberWithInt:indexPath.row]];
}

#pragma mark - Search Methods

-(void)textFieldDidChange:(UITextField*)textField
{
    searchTextString = textField.text;
    [self updateSearchArray];
}
//update seach method where the textfield acts as seach bar
-(void)updateSearchArray
{
    if (searchTextString.length != 0) {
        searchArray = [NSMutableArray array];
        for ( NSDictionary* item in dummyArray ) {
            if ([[[item objectForKey:@"name"] lowercaseString] rangeOfString:[searchTextString lowercaseString]].location != NSNotFound) {
                [searchArray addObject:item];
            }
        }
    } else {
        searchArray = dummyArray;
    }

    [self.contentTableView reloadData];
}

#pragma mark - Table view delegate

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(NSNumber*)indexNumber
{
    if([[segue identifier] isEqualToString:@"DummyDetail"]){

        NSInteger index = [indexNumber integerValue];

        SEDetailVC *dummyDetail = [segue destinationViewController];
        dummyDetail.dummyImageString = [[searchArray objectAtIndex:index] objectForKey:@"image"];
        dummyDetail.dummyTextString = [[searchArray objectAtIndex:index] objectForKey:@"description"];
        dummyDetail.title = [[searchArray objectAtIndex:index] objectForKey:@"name"];
    }
}

- (void)viewDidUnload {
    [self setSearchTextField:nil];
    [self setContentTableView:nil];
    [super viewDidUnload];
}
@end

Upvotes: 0

Related Questions