2012-09-19 5 views
0

는 내가 배열 tableViewArray와의 tableview을 만들어 가지고있는 tableviewuisearchbar uisearchdisplaycontroller에있는 tableview 자막 오류

내 검색 창에 약간의 문제가 있습니다.
tableViewArray는 [text, distance]로 구성된 다른 배열의 많은 행으로 구성됩니다. 모든 것이 잘 작동합니다.
이제 searchBar와 searchdisplaycontroller를 추가했습니다.이 배열은 tableViewArray의 "text"객체에있는 문자열 배열을 기반으로 검색했습니다. 나는 그 텍스트에 대해서만 검색이 가능해야한다고 생각했고, 검색 방법은 그것에 구현되었다.

이제 검색 결과를 얻으면 모양이 좋아지고 예상되는 행이 반환됩니다. 문제는 search tableViews 자막입니다. 그것은 tableViewArray 행 1, 2, 3에 대한 거리를 보여줍니다.

검색 tableview 행에 표시된 텍스트와 거리를 매핑해야합니다. [text distance]로 구성된 검색 결과에 대해 새 테이블 뷰 배열을 만들어야한다고 생각합니다. 텍스트는 검색 결과에서 나온 것이므로 문제가되지 않지만 이전 거리로 새 거리를 매핑하는 방법 ???

검색 위임에 사용하는 검색 방법 메신저는 다음과 같습니다

searchResults = [[NSArray alloc]init]; 
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", 
          searchText]; 
searchResults = [searchItems filteredArrayUsingPredicate:resultPredicate]; 

희망 누군가가 사전에 :) 감사합니다 도움이 될 수 있습니다!

원래 코드 :

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

    if (theTableView == self.searchDisplayController.searchResultsTableView) { 
     return [searchResults count]; 
    } else { 
     return [tableViewArray count]; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:  UITableViewCellStyleSubtitle 
            reuseIdentifier: CellIdentifier] ; 

    if (theTableView == self.searchDisplayController.searchResultsTableView) { 

    } else { 
     cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier  forIndexPath:indexPath]; 
} 

    // Configure the cell... 
    // cell.textLabel.numberOfLines = 0; 
    // cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; 

    if (theTableView == self.searchDisplayController.searchResultsTableView) { 
     cell.textLabel.text = [searchResults objectAtIndex:indexPath.row]; 
    } else { 
     cell.textLabel.text = [[[tableViewArray objectAtIndex:indexPath.row]  objectAtIndex:0] subtitle]; 
} 

    cell.detailTextLabel.textColor = [UIColor redColor]; 




float blabla= [[[tableViewArray objectAtIndex:indexPath.row] objectAtIndex: 1] doubleValue]; 
if (blabla < 1000) { 
     cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f m",blabla]; 
} else { 
     cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f km",blabla/1000]; 
} 





NSString *text = [[[tableViewArray objectAtIndex:indexPath.row] objectAtIndex:0] subtitle]; 
NSRange q8RangeValue = [text rangeOfString:@"Q8" options:NSCaseInsensitiveSearch]; 
NSRange okRangeValue = [text rangeOfString:@"OK" options:NSCaseInsensitiveSearch]; 

if (q8RangeValue.length >0 ) { 
     cell.imageView.image = [UIImage imageNamed:@"q8.png"]; 
} else if (okRangeValue.length >0) { 
     cell.imageView.image = [UIImage imageNamed:@"OK logo.png"]; 

} else { 
     cell.imageView.image = nil; 
} 

return cell; 
} 

그리고 난 검색 배열 할 여기서

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 

NSLog(@"didUpdateToLocation Location calculator distance array for the tableView"); 

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



for (int i = 0; i<allAnnotations.count; i++) { 

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0] ; 
CLLocationCoordinate2D annotationCoord = [[allAnnotations objectAtIndex:indexPath.row] coordinate]; 


CLLocation *location = [[CLLocation alloc] initWithLatitude:annotationCoord.latitude longitude:annotationCoord.longitude]; 

distanceToMe = [newLocation distanceFromLocation:location]; 

[distancesInReverseOrder insertObject:[NSNumber numberWithFloat: distanceToMe] atIndex:0]; 

} 


distances = [[NSMutableArray alloc] initWithArray:[[distancesInReverseOrder reverseObjectEnumerator] allObjects]]; 

// Assuming you have your points on the map in an NSArray called 
// allAnnotations and your distances in distances, create a 
// new mutable array to hold both 
tableViewArray = [[NSMutableArray alloc] init]; 

// Iterate over all of the points, and add a new element to the mutable 
// array which is a new array containing a point and its distance 
for (int i = 0; i < allAnnotations.count; i++) { 
    NSArray *newItem = [NSArray arrayWithObjects: [allAnnotations objectAtIndex: i], [distances objectAtIndex: i], nil]; 
    [tableViewArray addObject: newItem]; 
} 

// Now, sort the new array based upon the distance in the second element 
// of each array (ie, the distance). 
[tableViewArray sortUsingComparator: ^(id obj1, id obj2) { 
    NSNumber *dist1 = [obj1 objectAtIndex:1]; 
    NSNumber *dist2 = [obj2 objectAtIndex:1]; 

    return [dist1 compare:dist2]; 
}]; 

searchResults = [NSMutableArray arrayWithCapacity:[tableViewArray count]]; 




searchItems = [[NSMutableArray alloc] init]; 

for (int i = 0; i < allAnnotations.count; i++) { 
    NSArray *newItem = [NSArray arrayWithObjects: [[[tableViewArray objectAtIndex:i] objectAtIndex:0] subtitle], @"bla", nil]; 
    [searchItems addObject: newItem]; 
} 

/* 
for (int i=0; i<tableViewArray.count; i++) { 
    [searchItems insertObject:[[[tableViewArray objectAtIndex:i] objectAtIndex:0] subtitle] atIndex:0]; 
} 
*/ 

NSLog(@"searchitems count is %i", searchItems.count); 

[tableView reloadData]; 

[locationManager stopUpdatingLocation]; 

}를

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope 
{ 
/* 
// Update the filtered array based on the search text and scope. 
// Remove all objects from the filtered search array 
[searchResults removeAllObjects]; 
// Filter the array using NSPredicate 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText]; 

//의 SearchResult = [NSMutableArray를 arrayWithArray : [ tableViewArray objectAtIndex : 1] filteredArrayUsingPredicate : 술어]]; */

/* 

의 SearchResult = [NSArray를 ALLOC의] INIT];

NSPredicate *resultPredicate = [NSPredicate 
           predicateWithFormat:@"SELF contains[cd] %@", 
           searchText]; 

    searchResults =[searchItems filteredArrayUsingPredicate:resultPredicate]; 


*/ 

// Create index set of all objects in textArray that contain searchText: 
NSIndexSet *set = [searchItems indexesOfObjectsPassingTest: 
        ^BOOL(NSString *text, NSUInteger idx, BOOL *stop) { 
         NSRange range = [text rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]; 
         return (range.location != NSNotFound); 
        }]; 

// Filter textArray: 
filteredTextArray = [searchItems objectsAtIndexes:set]; 
// Filter distanceArray: 
filteredDistanceArray = [distances objectsAtIndexes:set]; 

NSLog(@"filtered text array is %@", filteredTextArray); 
NSLog(@"filtered distance array is %@",filteredDistanceArray); 
+0

검색 결과 배열에있는 객체를 복사하여 tableview 배열에 복사 했습니까 ?? –

+0

어떻게 할 수 있습니까? searchResults 배열은 전적으로 tableview 배열의 인덱스 0으로 구성됩니다. 따라서 인덱스 1 (거리)을 전혀 고려하지 않습니다. –

답변

2

내가 제대로 문제를 이해한다면, 당신은 테이블 뷰에 대한 데이터 소스로 사용되는 2 개 개의 분리 배열을 가지고,의 그들을 textArraydistanceArray를 호출 할 수 있습니다.

이제 검색 문자열에 따라 textArray을 필터링하면 distanceArray의 "해당하는"필터링이 필요합니다. 당신이 데이터 소스로 filteredTextArrayfilteredDistanceArray을 사용할 수 있습니다 지금

// Create index set of all objects in textArray that contain searchText: 
NSIndexSet *set = [textArray indexesOfObjectsPassingTest: 
    ^BOOL(NSString *text, NSUInteger idx, BOOL *stop) { 
     NSRange range = [text rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]; 
     return (range.location != NSNotFound); 
    }]; 

// Filter textArray: 
filteredTextArray = [textArray objectsAtIndexes:set]; 
// Filter distanceArray: 
filteredDistanceArray = [distanceArray objectsAtIndexes:set]; 

: 그 두 배열에 적용 할 수있는 일치하는 인덱스 세트를 반환하기 때문에이 작업을 수행하는

한 가지 방법은, indexesOfObjectsPassingTestfilteredArrayUsingPredicate을 대체하는 것입니다 검색 테이블 뷰.어레이 내의 각각의 오브젝트는, 예를 들면 한 행에 텍스트와의 거리를 모두 함유하는 경우 사전

대안이 경우의 데이터 소스와 같은 하나의 어레이를 사용할 수있다.

UPDATE : 지금 그것을 이해으로, 당신의 tableViewArray의 각 항목 2 개 항목 (텍스트에 대한 하나의 거리에 대해 하나의)와 배열입니다.

이때 I는 tableViewArray 직접 필터링 추천 할 것 :

NSIndexSet *set = [tableViewArray indexesOfObjectsPassingTest: 
        ^BOOL(NSArray *item, NSUInteger idx, BOOL *stop) { 
         NSString *subtitle = [[item objectAtIndex:0] subtitle]; 
         NSRange range = [subtitle rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]; 
         return (range.location != NSNotFound); 
        }]; 

searchResults = [tableViewArray objectsAtIndexes:set]; 

지금 searchResults 필터링 된 어레이이고, 각 상품 tableViewArray의 항목과 동일한 구조를 갖는다.

이렇게하면 cellForRowAtIndexPath의 내용이 단순화됩니다.

if (theTableView == self.searchDisplayController.searchResultsTableView) { 
    cell.textLabel.text = [[[searchResults objectAtIndex:indexPath.row] objectAtIndex:0] subtitle]; 
    distance = [[[searchResults objectAtIndex:indexPath.row] objectAtIndex: 1] doubleValue]; 
} else { 
    cell.textLabel.text = [[[tableViewArray objectAtIndex:indexPath.row] objectAtIndex:0] subtitle]; 
    distance = [[[tableViewArray objectAtIndex:indexPath.row] objectAtIndex: 1] doubleValue]; 
} 
+0

안녕하세요, 글쎄 tableview의 데이터 소스에 대해 동일한 배열을 사용합니다. 하지만이 배열은 두 배열의 조합입니다. tableview 배열의 인덱스 0은 locationArray에서 가져오고 인덱스 1은 거리 배열에서 가져옵니다. 나는 기본적으로이 경우 "searchitems"(locaion 배열의 복사본) 인 위치 배열에 대한 내 검색을 수행합니다. 따라서 tableViewArray는 (인덱스 0 위치, 인덱스 1 거리)입니다. 작성한 코드에서 실제 검색이 수행되는 대상은 어디에서 정의합니까? (나는 한편으로 당신의 솔루션을 시도 할 것입니다. 나는 대답이되어야한다고 생각했던 것입니다.) –

+0

@ B-Man : 내 코드는 배열'textArray'에서'searchText'를 검색합니다. - 배열이 어떻게 작동하는지 아직 이해하지 못합니다. 'cellForRowAtIndexPath :'코드를 보여 주면 도움이 될 것입니다. - 또는 내 솔루션을 먼저 시도하고 궁금한 점이 있으시면 회신하십시오 ... 원하는대로. –

+0

원본 코드가 위에 업데이트되었습니다. 한번 봐주세요. 감사! :) –