【问题标题】:UISearchBar in storyboard Xcode故事板 Xcode 中的 UISearchBar
【发布时间】:2012-05-06 23:04:04
【问题描述】:

我想在 storyboard xcode 中为我的表创建 searchBar,一切都对我有用,我没有任何错误,只是搜索不起作用。

我看过这两个教程,但仍然不起作用。我无法搜索。 我的教程:

   -http://stackoverflow.com/questions/9897171/uisearchbar-implemented-with-storyboards
   -http://www.youtube.com/watch?v=IqDZHgI_s24

你能帮帮我吗? 提前致谢!

这是我的代码

CreateViewController.h

#import <UIKit/UIKit.h>

@interface CreateViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource,       UISearchBarDelegate>
{
// @property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
NSArray *datas;
NSMutableArray *displayItems;
IBOutlet UITableView * tableView;
IBOutlet UISearchBar * searchbar;
}

@end

CreateViewController.m

#import "CreateViewController.h"

@interface CreateViewController ()

@end

@implementation CreateViewController

- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];

datas = [NSMutableArray arrayWithObjects:@"Johan", @"Paul",@"George",@"Ringo", nil];
displayItems = [[NSMutableArray alloc] initWithArray:datas];
[super viewDidLoad];
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";//This is the identifier in storyboard    
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}

cell.textLabel.text = [datas objectAtIndex:indexPath.row];
return cell;
}
-(void)searchbar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText{
if([searchText length] == 0){
    [displayItems removeAllObjects];
    [displayItems addObjectsFromArray:datas];
}else{
    [displayItems removeAllObjects];
    for(NSString * string in datas){
        NSRange r = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (r.location != NSNotFound){
            [displayItems addObject:string];   
        }
    }
}
[tableView reloadData];
}

 #pragma mark - Table view delegate

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib    name#>" bundle:nil];
 // ...
 // Pass the selected object to the new view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 */
}

@end

【问题讨论】:

    标签: uitableview uisearchbar uistoryboard


    【解决方案1】:

    使用本教程 iOS 快速提示:使用搜索栏过滤 UITableView

    http://code-ninja.org/blog/2012/01/08/ios-quick-tip-filtering-a-uitableview-with-a-search-bar/

    -(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
    {
    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        isFiltered = true;
        filteredTableData = [[NSMutableArray alloc] init];
    
        for (Food* food in allTableData)
        {
            NSRange nameRange = [food.name rangeOfString:text options:NSCaseInsensitiveSearch];
            NSRange descriptionRange = [food.description rangeOfString:text options:NSCaseInsensitiveSearch];
            if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
            {
                [filteredTableData addObject:food];
            }
        }
    }
    
    [self.tableView reloadData];
    }
    

    【讨论】:

    • 如果您的表格视图中有部分怎么办?知道您将在各个部分的内容而不是单个数组中进行搜索,如何进行搜索?
    • jaytrixz,您可能会发现我的其他关于过滤分组 UITableView 的教程很有用。它使用数组字典而不是单个数组。 code-ninja.org/blog/2012/07/04/…
    【解决方案2】:

    你可以使用 NSPredicate 来实现这个功能,修改你的搜索委托方法如下

        [datas release];
    datas = nil;
    
    datas = [[NSMutableArray alloc] initWithArray: displayItems];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[c] %@",[NSString stringWithFormat:@"%@*",searchBar.text]];
    [datas filterUsingPredicate:predicate];
    [tableView reloadData];
    

    在此处查看示例代码

    http://dl.dropbox.com/u/58723521/SearchSample.zip

    【讨论】:

    • 你可能使用了其他 UISearchBar 实例,替换为该名称。
    【解决方案3】:

    我同意,您需要更改 cellForRowAtIndexPathnumberOfRowsInSection 以使用 displayItems 数组而不是 datas 数组。 还要检查您是否为搜索栏设置了UISearchBarDelegate

    【讨论】:

      【解决方案4】:

      您需要更改 cellForRowAtIndexPath 以使用 displayItems 数组而不是 datas 数组

      - (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      {
      static NSString *CellIdentifier = @"Cell";//This is the identifier in storyboard    
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
      if(!cell) {
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
      
      }
      
      cell.textLabel.text = [displayItems objectAtIndex:indexPath.row];
      return cell;
      }
      

      并且还将 numberOfRowsInSection 更改为使用 displayItems 数组计数

       - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
      {
      
      // Return the number of rows in the section.
      return [displayItems count];
      }
      

      【讨论】:

      • 谢谢,但什么都没发生
      【解决方案5】:

      这样做,

      • 在你的头文件中声明这样的数组,

        NSMutableArray *datas;
        NSMutableArray *displayItems;
        
      • 然后像这样在viewDidLoad中改变数组初始化,

        datas = [[NSMutableArray alloc] initWithObjects:@"Johan", @"Paul",@"George",@"Ringo", nil];
        displayItems = [[NSMutableArray alloc] initWithArray:datas];
        
      • cellForRowAt方法中改变数组,

        cell.textLabel.text = [displayItems objectAtIndex:indexPath.row];
        
      • 然后使用 NSLog 在 textDidChange 方法中打印您的搜索字符串。如果不打印,则 IBOutlet 连接有问题。如果能打印,更换这个方法,看看是否有效,

        -(void)searchbar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText{
        
        if([searchText length] == 0){
        
        }else{
            [displayItems removeAllObjects];
            for (int i=0; i<[datas count]; i++) {
                if ([searchText hasPrefix:[datas objectAtIndex:i]]) {
                    [displayItems addObject:[datas objectAtIndex:i]];
                } else {
        
                }
            }
        }
        [tableView reloadData];
        }
        

      我的排序方法不是世界上最好的。但请尝试让您的代码正常工作。

      编辑:我认为你的代表没有被解雇。试试这个方法而不是上面的方法。

      - (void) searchBarSearchButtonClicked:(UISearchBar*) theSearchBar
      {
      if([searchBar.text length] == 0){
      arrayDisplayData = arrayOriginalData;
      }else{
          [arrayDisplayData removeAllObjects];
          for(NSString * string in arrayOriginalData){
              NSRange r = [string rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
              if (r.location != NSNotFound){
                  [arrayDisplayData addObject:string];   
              }
          }
      }
      [tblResults reloadData];
      }
      

      或者这个,

      - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
      

      【讨论】:

      • 您的表格视图是否显示您在启动应用程序时放置的数据?我的意思是这些,“datas = [NSMutableArray arrayWithObjects:@"Johan", @"Paul",@"George",@"Ringo", nil];"
      • @deamonsarea 谢谢,我试试第二个没用,第一个我有错误 searchBar.text 和 [tblResults reloadData];
      猜你喜欢
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 2015-09-16
      • 2012-01-22
      • 2012-01-13
      • 1970-01-01
      相关资源
      最近更新 更多