2012-09-12 3 views
0

검색 창에 대한 tableview 검색에 대해 자세히 알아 보려면 작은 프로그램을 만들려고합니다. 그 사이에 나는 이것을하려고하는 제 3의 주에있다. 인터넷에서 여러 가지 예를 발견했습니다. searchdisplaycontroller를 사용하는 것이 가장 많지만이 방법은 viewcontroller에만 해당됩니다. 나는 또한 uiview와 함께 작동하는 방법을 선호하므로 검색 바 대리자 메서드를 사용하여 데이터 사전을 필터링합니다. 일반적으로 나는 오랫동안 혼자서 이런 일을 처리하려고 노력합니다. 그러나 이것은 나의 천적입니다. 이 문제를 해결할 수있는 방법을 찾지 못했습니다. 누구든지 내 코드를 도와 줄 수 있습니까? 여기 있습니다.섹션이있는 TableView 필터링

#import "FilterDemoTableViewController.h" 

@implementation FilterDemoTableViewController 

@synthesize filteredTableData; 
@synthesize searchBar; 
@synthesize isFiltered; 

@synthesize tableContents; 
@synthesize Keys; 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    searchBar.delegate = (id)self; 


    //-----------------------My TableView Data ------------------------------ 

    NSArray *array1 = [[NSArray alloc]initWithObjects:@"Berlin",@"München",@"Stuttgart",nil]; 
    NSArray *array2 = [[NSArray alloc]initWithObjects:@"Paris",@"Bordeaux",@"Marseille",@"Toulouse",nil]; 
    NSArray *array3 = [[NSArray alloc]initWithObjects:@"London",@"Portsmouth",@"Oxford",@"York",@"Dover",nil]; 
    NSArray *array4 = [[NSArray alloc]initWithObjects:@"Rom" ,@"Genua",@"Mailand",@"Florenz",nil]; 
    NSArray *array5 = [[NSArray alloc]initWithObjects:@"Madrid",@"Barcelona",@"Toledo",@"Saragossa",@"Pamplona",nil]; 
    NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,@"Deutschland",array2,@"Frankreich",array3,@"Großbritannien",array4,@"Italien",array5,@"Spanien",nil]; 

    self.tableContents = dictionary; 
    self.Keys = [self.tableContents allKeys]; 

    //--------------------------------------------------------------------------  
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    if (self.isFiltered) { 
     return [filteredTableData count]; 
    } else { 
     return [Keys count];} 
} 

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

    NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]]; 

    int rowCount; 
    if(self.isFiltered) 
     rowCount = filteredTableData.count; 
    else 
     rowCount = [listData count]; 

    return rowCount; 

} 


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

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 



    NSDictionary* sectionDictionary; 

    if (isFiltered) { 
     sectionDictionary = [filteredTableData objectAtIndex:indexPath.section]; 
    } else { 
     sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]]; 
    } 

    NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]]; 

    cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row]; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    return cell; 
} 



-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text 
{ 
    if(text.length == 0) 
    { 
     isFiltered = FALSE; 
    } 
    else 
    { 
    //I think here is something wrong but i don't know what 

     isFiltered = true; 

     filteredTableData = [[NSMutableArray alloc] init]; 

     NSMutableArray *searchArray = [[NSMutableArray alloc] init]; 

     for (NSDictionary *dictionary in tableContents) //dictionary read 
     { 
      NSArray *array = [dictionary objectForKey:Keys]; //section of dictionary read 
      [searchArray addObjectsFromArray:array];   
     } 

     for (NSString *sTemp in searchArray)  
     { 
      NSRange titleResultsRange = [sTemp rangeOfString:text options:NSCaseInsensitiveSearch]; 

      if (titleResultsRange.length != 0)   
       [filteredTableData addObject:sTemp]; 
     } 
    } 
    [self.tableView reloadData]; 
} 



- (void)viewDidUnload{ 
    [self setSearchBar:nil]; 
    [super viewDidUnload]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 


@end 

답변

0

이제 전체 새로 고침 된 코드를 게시합니다. 코드의 각 구성 요소를 단계별로 테스트했습니다. 그것은 작동하며 검색도 괜찮습니다 (UITableViewController에서). 그러나이 예제에서 구멍 코드는 UIView에 있습니다. 이유는, 이런 식으로 전체 크기가 아닌 테이블 뷰를 생성하고 테이블 뷰를 생성 할 수 있기 때문입니다. 명확한 ViewController를 사용하면 훨씬 좋습니다. UIView에이 방법이 없다는 것을 알고 있습니다. reloadData하지만 필요합니다. 코드 끝 부분에서 문제가있는 행을 볼 수 있습니다. 그리고 마지막 단계에서 나는 이것을 어떻게 풀 수 있는지 전혀 모른다. [self.tableView reloadData];

#import "TableView.h" 
#import <QuartzCore/QuartzCore.h> 

@interface TableView() 

@end 

@implementation TableView 
@synthesize delegate; 
@synthesize dropDownHeight; 
@synthesize labelText; 
@synthesize enabled; 

@synthesize tableContents; 
@synthesize Keys; 

@synthesize searchBar; 
@synthesize isFiltered; 
@synthesize filteredTableData; 


- (void)__show { 
    viewControl.alpha = 0.0f; 
    UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow]; 
    [mainWindow addSubview:viewControl]; 
    [UIView animateWithDuration:0.3f 
       animations:^{ 
        viewControl.alpha = 1.0f; 
       } 
       completion:^(BOOL finished) {}]; 
} 
- (void)__hide { 
    [UIView animateWithDuration:0.2f 
       animations:^{ 
        viewControl.alpha = 0.0f; 
       } 
       completion:^(BOOL finished) { 
        [viewControl removeFromSuperview]; 
       }]; 
} 
- (void) setLabelText:(NSString *)_labelText{ 
    [button setTitle:labelText forState:UIControlStateNormal]; 
} 
- (void) setEnable:(BOOL)_enabled{ 
    enabled = _enabled; 
    [button setEnabled:_enabled]; 
} 
- (void) setArrayData:(NSArray *)_arrayData{ 
    [table reloadData]; 
} 
- (void) buttonPressed{ 
    [self __show]; 
} 
- (void) controlPressed{ 
//[viewControl removeFromSuperview]; 
    [self __hide]; 
} 


- (id) initWithFrame:(CGRect)frame 
{ 

self = [super initWithFrame:frame]; 
if (self) { 
    // Initialization code 
    button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [button setFrame:CGRectMake(10, 0, 280, 30)]; 
    [button setTitle:@"--Auswahl--" forState:UIControlStateNormal]; 
    [button setBackgroundImage:[UIImage imageNamed:@"combo_bg.png"] forState:UIControlStateNormal]; 
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; 
    [button.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]]; 
    [self addSubview:button]; 
    dropDownHeight = 706; 

    viewControl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; 
    [viewControl addTarget:self action:@selector(controlPressed) forControlEvents:UIControlEventTouchUpInside]; 

    CGFloat x = self.frame.origin.x; 
    CGFloat y = (viewControl.frame.size.height - dropDownHeight)/2; 

    table = [[UITableView alloc] initWithFrame:CGRectMake(x, y, frame.size.width, dropDownHeight) style:UITableViewStyleGrouped]; 
    table.dataSource = self; 
    table.delegate = self; 

    searchBar = [[UISearchBar alloc] init]; 
    [searchBar sizeToFit]; 
    searchBar.delegate = (id)self; 
    table.tableHeaderView = searchBar; 

    CALayer *layer = table.layer; 
    layer.masksToBounds = YES; 
    layer.cornerRadius = 2.0f; 
    layer.borderWidth = 1.0f; 
    [layer setBorderColor:[UIColor darkGrayColor].CGColor]; 
    [viewControl addSubview:table]; 

    CGAffineTransform rotateTable = CGAffineTransformMakeRotation(M_PI_2); 
    table.transform = rotateTable; 
    table.frame = CGRectMake(-2, -1, table.frame.size.width, table.frame.size.height); 

    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gradientBackground.png"]]; 
    [tempImageView setFrame:self->table.frame]; 
    table.backgroundView = tempImageView; 


    //----------------------- TableView Daten ------------------------------ 

    NSArray *array1 = [[NSArray alloc]initWithObjects:@"Berlin",@"München",@"Stuttgart",@"Hamburg",nil]; 
    NSArray *array2 = [[NSArray alloc]initWithObjects:@"Paris",@"Bordeaux",@"Marseille",@"Toulouse",nil]; 
    NSArray *array3 = [[NSArray alloc]initWithObjects:@"London",@"Portsmouth",@"Oxford",@"York",@"Dover",nil]; 
    NSArray *array4 = [[NSArray alloc]initWithObjects:@"Rom" ,@"Genua",@"Mailand",@"Florenz",nil]; 
    NSArray *array5 = [[NSArray alloc]initWithObjects:@"Madrid",@"Barcelona",@"Toledo",@"Saragossa",@"Pamplona",nil]; 
    NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,@"Deutschland",array2,@"Frankreich",array3,@"Großbritannien",array4,@"Italien",array5,@"Spanien",nil]; 

    self.tableContents = dictionary; 
    self.Keys = [self.tableContents allKeys]; 

    // --------------------------------------------------------------------- 
    } 
return self; 
} 


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
if ([self tableView:tableView titleForHeaderInSection:section] != nil) { 
    return 40; 
} 
else { 
    return 0; 
} 
} 

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  { 
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section]; 
if (sectionTitle == nil) { 
    return nil; 
} 

// Create label with section title 
UILabel *label = [[UILabel alloc] init]; 
label.frame = CGRectMake(20, 6, 300, 30); 
label.backgroundColor = [UIColor clearColor]; 
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]; 
label.shadowColor = [UIColor grayColor]; 
label.shadowOffset = CGSizeMake(0.0, 1.0); 
label.font = [UIFont boldSystemFontOfSize:16]; 
label.text = sectionTitle; 

// Create header view and add label as a subview 
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; 
[view addSubview:label]; 

return view; 
} 


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
return 60.0; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section { 

return [self.Keys objectAtIndex:section]; 

} 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
if (self.isFiltered) 
{ 
    return 1; 
} else { 
    return [Keys count];} 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
int rowCount; 
if(self.isFiltered) 
{ 
    rowCount = [filteredTableData count]; 
} 
else 
{ 
    NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]]; 
    rowCount = [listData count]; 
} 
return rowCount; 

} 


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

static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier]; 

if(cell == nil) { 

    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier]; 
} 

if (isFiltered) 
{ 
    NSString * stadt = [filteredTableData objectAtIndex:indexPath.row]; 
    cell.textLabel.text = stadt; 
} 
else 
{ 
    NSDictionary* sectionDictionary; 
    sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]]; 
    NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]]; 
    cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row]; 
} 

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

return cell;  
} 



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

NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:[indexPath section]]]; 
NSUInteger row = [indexPath row]; 
NSString *rowValue = [listData objectAtIndex:row]; 
[tableView deselectRowAtIndexPath:indexPath animated:YES]; 

selectedIndex = [indexPath row]; 

[self __hide]; 
[button setTitle:[[NSString alloc] initWithFormat:rowValue] forState:UIControlStateNormal]; 

} 


- (NSInteger) selectedIndex { 

return selectedIndex; 
} 


-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text 
{ 
if(text.length == 0) 
{ 
    isFiltered = FALSE; 
} 
else 
{ 
    isFiltered = true; 
    [filteredTableData removeAllObjects]; 

    for (NSString* key in self.tableContents) 
    { 

     NSArray *staedte = [self.tableContents objectForKey:key]; 

     for (NSString *stadt in staedte) 
     { 

      NSRange titleResultsRange = [stadt rangeOfString:text options:NSCaseInsensitiveSearch]; 

      if (titleResultsRange.length != 0) 
      { 
       [filteredTableData addObject:stadt]; 
      } 
     } 
    } 
} 
[self.tableView reloadData]; //Here is the error 
} 



-(void)didChangeTableViewValue:(TableView *)TableView selectedIndex:(NSInteger)selectedIndex { 

} 


@end