【问题标题】:Text Field As Search Bar文本字段作为搜索栏
【发布时间】:2014-04-21 16:22:11
【问题描述】:

有没有什么好的教程或方法可以将文本字段变成搜索栏?

我已经用搜索栏 + 搜索显示控制器设置了我的搜索栏,它工作正常 - 但很难自定义...特别是摆脱丑陋的灰色覆盖,显然这是最好的方法。

我无法找到任何有关这样做的信息,并认为必须有人以前做过。

【问题讨论】:

标签: ios objective-c search uitextfield uisearchbar


【解决方案1】:

从这里下载完整的源代码https://github.com/shashidev/TextFieldAsSearchBar.git

#import "ViewController.h"

@interface ViewController()

<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    NSMutableArray *arrOfColor;
    NSMutableArray *searchArray;
    NSString *searchTextString;
    BOOL isFilter;
}

@property (strong, nonatomic) IBOutlet UITextField *searchTextField;
@property (strong, nonatomic) IBOutlet UITableView *colorTableview;

@end

实现.m 文件。

@implementation ViewController

- (void)viewDidLoad 

{
    [super viewDidLoad];
    arrOfColor=[NSMutableArray arrayWithObjects:@"Red",@"Green",@"Blue",@"Gray",@"Black",@"White",@"Yellow",@"Brown",@"Pink",nil];
    [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if(isFilter)
    {
        return [searchArray count];
    }
    else
        return  [arrOfColor count];
}

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

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if(isFilter)
    {
        cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
    }
    else
    {
          cell.textLabel.text=[arrOfColor objectAtIndex:indexPath.row];
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(isFilter)
    {
        _searchTextField.text=[searchArray objectAtIndex:indexPath.row];
    }
    else
    {
        _searchTextField.text=[arrOfColor objectAtIndex:indexPath.row];

    }
}

-(void)textFieldDidChange:(UITextField *)textField
{
    searchTextString=textField.text;
    [self updateSearchArray:searchTextString];
}

-(void)updateSearchArray:(NSString *)searchText
{
    if(searchText.length==0)
    {
        isFilter=NO;
   }
   else
   {
        isFilter=YES;
        searchArray=[[NSMutableArray alloc]init];
        for(NSString *string in arrOfColor){

            NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if(stringRange.location !=NSNotFound){

                [searchArray addObject:string];
            }
        }
         [self.colorTableview reloadData];}
    }

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
@end

【讨论】:

  • 您的代码很完美,但它也更新了我的数组 ID。它根据 tableview 索引而变化。你能帮帮我吗。
  • 谢谢你,我使用NSPredicate 的循环只是很小的变化而不是循环,如果数组很大,速度会更快。
【解决方案2】:

我不知道任何涵盖该主题的教程,但前一段时间在其他人的帮助下,我能够做到这一点。这是 .h 和 .m 文件中的总代码。我可以解释整个事情,但它在每一行都有注释,所以我想它已经足够清楚了。

.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

我希望以上内容足够清晰和有帮助,如果您需要任何帮助,请告诉我。

【讨论】:

  • Hello @XCode Monkey。我正在从服务器获取数据并显示在 tableview 中。我必须将文本字段实现为搜索栏并在该文本字段中搜索。我已经尝试过你的代码,但我没有得到.请帮帮我
  • @AppDeveloper,应该看到你的代码,很难提供帮助。上面的代码是为一个简单的数组设置的,它的成员在同一个类上声明。这可能与您用于从服务器提取数据的方法有关。
  • - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"strSubCatName contains[cd] %@ ",textField.text]; searchArray =[NSMutableArray arrayWithArray:[arrSubCatOb filteredArrayUsingPredicate:predicate]]; NSLog(@"搜索数组为:%@",searchArray); [self.tableViewForSubCat reloadData];返回是; }
  • 我正在使用此代码使用自定义搜索文本字段过滤 tableview 数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多