2012-04-26 26 views
6

Tôi muốn tạo bảng tìm kiếm cho bảng của tôi trong bảng phân cảnh xcode, mọi thứ đều hoạt động đối với tôi và tôi không có bất kỳ lỗi nào, chỉ tìm kiếm không hoạt động.UISearchBar trong kịch bản Xcode

Tôi đã thấy hai hướng dẫn này nhưng vẫn không hoạt động. Tôi không thể tìm kiếm. hướng dẫn của tôi:

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

bạn sẽ vui lòng giúp tôi, Cảm ơn trước!

Đây là mã của tôi

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 

Trả lời

0

làm nó như thế này,

  • Trong tập tin tiêu đề của bạn khai báo mảng như này,

    NSMutableArray *datas; 
    NSMutableArray *displayItems; 
    
  • Sau đó thay đổi mảng khởi tạo trong viewDidLoad như thế này,

    datas = [[NSMutableArray alloc] initWithObjects:@"Johan", @"Paul",@"George",@"Ringo", nil]; 
    displayItems = [[NSMutableArray alloc] initWithArray:datas]; 
    
  • Thay đổi mảng trong cellForRowAt phương pháp,

    cell.textLabel.text = [displayItems objectAtIndex:indexPath.row]; 
    
  • Sau đó in tìm kiếm của bạn chuỗi bên trong textDidChange phương thức sử dụng NSLog. Nếu nó không được in, có gì đó sai với kết nối IBOutlet. Nếu nó in, thay thế phương pháp này và xem nếu nó hoạt động,

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

phương pháp sắp xếp của tôi không phải là tốt nhất trên thế giới. Nhưng hãy cố gắng làm cho mã của bạn hoạt động.

Chỉnh sửa: Tôi nghĩ rằng đại biểu của bạn không kích hoạt. Hãy thử phương pháp này thay vì ở trên.

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

Hoặc này,

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

Cám ơn câu trả lời của bạn, nhưng vẫn không hoạt động! –

+0

Chế độ xem bảng của bạn có hiển thị dữ liệu bạn đã đặt khi bạn khởi động ứng dụng không ?. Ý tôi là, "datas = [NSMutableArray arrayWithObjects: @" Johan ", @" Paul ", @" George ", @" Ringo ", nil];" –

+0

có nó hiển thị chúng. –

0

Bạn cần thay đổi bạn cellForRowAtIndexPath sử dụng các mảng displayItems chứ không phải là mảng dữ liệu ngay

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

Và cũng thay đổi numberOfRowsInSection sử dụng các mảng displayItems đếm

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

// Return the number of rows in the section. 
return [displayItems count]; 
} 
+0

Cảm ơn, nhưng Notthing đã xảy ra –

1

bạn có thể sử dụng NSPredicate cho chức năng này, thay đổi phương pháp đại biểu tìm kiếm của bạn như sau

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

kiểm tra các mẫu mã ở đây

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

+0

Tôi đã có lỗi về phần này, searchBar.text] –

+0

Tôi sẽ kiểm tra liên kết nhờ –

+0

u có thể đã sử dụng một số cá thể UISearchBar khác, thay thế bằng tên đó. – vishy

1

Tôi đồng ý, bạn cần thay đổi cellForRowAtIndexPathnumberOfRowsInSection của bạn để sử dụng mảng displayItems thay vì mảng dữ liệu. Đồng thời kiểm tra xem bạn đã đặt UISearchBarDelegate cho thanh tìm kiếm của mình chưa.

8

Sử dụng hướng dẫn này iOS Mẹo nhanh: Lọc một UITableView với một thanh tìm kiếm

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]; 
} 
+0

Điều gì sẽ xảy ra nếu bạn có các phần trong bảng chiếu? Làm thế nào có thể tìm kiếm công việc biết rằng bạn sẽ được tìm kiếm bên trong nội dung của các phần thay vì một mảng duy nhất? – jaytrixz

+0

jaytrixz, bạn có thể tìm thấy hướng dẫn khác của tôi về lọc một UITableView nhóm hữu ích. Nó sử dụng một từ điển của mảng thay vì một mảng duy nhất. http://code-ninja.org/blog/2012/07/04/filtering-a-grouped-uitableview-with-a-search-bar/ –

Các vấn đề liên quan