如何将文本字段输入视图作为搜索栏?

How to make textfield input view as search bar?

我试图找到合适的解决方案,但我找不到任何程序员请告诉我如何制作。

1.is 可以将 uitextfield 设置为 uisearchbar 吗?

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

2.While 用户键入我需要的值 将其显示为文本字段底部的叠加...

3.Please 帮我找出解决办法..

在 .h 文件中

    #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

在 .m 文件中

@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

要使文本字段像搜索栏一样工作,请实施 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string UITextField 的委托方法。所以基本上,你需要实现自动完成功能,这就是你如何做的。 要检测触发了哪个文本字段,请使用向文本字段分配标签。

在您的 ViewController.h 文件中:

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

}

在您的 ViewController.m 文件中:

- (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];

}