UITableview cellForRowAtIndexPath方法没有执行?

时间:2013-05-16 06:21:13

标签: ios objective-c uitableview uisearchbar

当我点击搜索时,它会执行一个搜索类,在找到结果后,它会执行numberOfRows方法,但它会显示空表。它没有执行cellForRowAtIndexPath方法。 检查我的下面代码

viewcontroller.h

中的代码

当我点击搜索按钮时,此方法将被执行

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:@"SearchResultsViewController" bundle:nil];
    NSString *searchQuery=[search text];
    sharedManager=[Mymanager sharedManager];
    sharedManager.searchQuery=searchQuery;

    [searchRes searchString:searchQuery];


    [self.navigationController pushViewController:searchRes animated:YES];

}
搜索类

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%@",results);
           return [results count];

}

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

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

    cell.textLabel.adjustsFontSizeToFitWidth = YES;

       NSLog(@"indexpath%d",indexPath.row);
        NSLog(@"%@",[results objectAtIndex:[indexPath row]]);

        SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
        NSLog(@"%@",hit.neighboringText);
        cell.textLabel.text = [NSString stringWithFormat:@"...%@...", hit.neighboringText];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1];
        cell.textLabel.font = [UIFont fontWithName:@"Trebuchet MS" size:12];
        cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];

//    else
//    {
//        
//    }
   //  [[self resultsTableView] reloadData];
    return cell;
}

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

       SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];

    [fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];


}


- (void) searchString:(NSString*)query{
//    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//    {
    self.results = [[NSMutableArray alloc] init];
    [resultsTableView reloadData];
    currentQuery=sharedManager.searchQuery;
//    
    [self searchString:currentQuery inChapterAtIndex:0];
//
//    }else {
 //  currentQuery=sharedManager.searchQuery;
 //  [self searchString:currentQuery inChapterAtIndex:0];
//}
}

- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{

             currentChapterIndex = index;
    sharedManager=[Mymanager sharedManager];
    Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
    NSLog(@"%d",chapter.text.length);
    NSRange range = NSMakeRange(0, chapter.text.length);

    NSLog(@"%@",sharedManager.searchQuery);
      range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
    int hitCount=0;
    while (range.location != NSNotFound) {
        range = NSMakeRange(range.location+range.length, chapter.text.length-(range.location+range.length));
        range = [chapter.text rangeOfString:sharedManager.searchQuery  options:NSCaseInsensitiveSearch range:range locale:nil];
        hitCount++;
    }

    if(hitCount!=0){
         UIWebView* webView = [[UIWebView alloc] initWithFrame:chapter.windowSize];
        [webView setDelegate:self];
        NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:chapter.spinePath]];
        [webView loadRequest:urlRequest];
    } else {
        if((currentChapterIndex+1)<[sharedManager.spineArray count]){
            [self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
        } else {
            fvc.searching = NO;
        }
    }



}





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

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"%@", error);
    [webView release];
}

- (void) webViewDidFinishLoad:(UIWebView*)webView{
    NSString *varMySheet = @"var mySheet = document.styleSheets[0];";

    NSString *addCSSRule =  @"function addCSSRule(selector, newRule) {"
    "if (mySheet.addRule) {"
    "mySheet.addRule(selector, newRule);"                               // For Internet Explorer
    "} else {"
    "ruleIndex = mySheet.cssRules.length;"
    "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);"   // For Firefox, Chrome, etc.
    "}"
    "}";


    NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width];
    NSString *insertRule2 = [NSString stringWithFormat:@"addCSSRule('p', 'text-align: justify;')"];




        NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",[[sharedManager.spineArray objectAtIndex:currentChapterIndex] fontPercentSize]];

    [webView stringByEvaluatingJavaScriptFromString:varMySheet];

    [webView stringByEvaluatingJavaScriptFromString:addCSSRule];

    [webView stringByEvaluatingJavaScriptFromString:insertRule1];

    [webView stringByEvaluatingJavaScriptFromString:insertRule2];

       [webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
    [webView highlightAllOccurencesOfString:sharedManager.searchQuery];

    NSString* foundHits = [webView stringByEvaluatingJavaScriptFromString:@"results"];

       NSLog(@"%@", foundHits);

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

    NSArray* stringObjects = [foundHits componentsSeparatedByString:@";"];
    for(int i=0; i<[stringObjects count]; i++){
        NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:@","];
        if([strObj count]==3){
            [objects addObject:strObj];
        }
    }

    NSArray* orderedRes = [objects sortedArrayUsingComparator:^(id obj1, id obj2){
        int x1 = [[obj1 objectAtIndex:0] intValue];
        int x2 = [[obj2 objectAtIndex:0] intValue];
        int y1 = [[obj1 objectAtIndex:1] intValue];
        int y2 = [[obj2 objectAtIndex:1] intValue];
        if(y1<y2){
            return NSOrderedAscending;
        } else if(y1>y2){
            return NSOrderedDescending;
        } else {
            if(x1<x2){
                return NSOrderedAscending;
            } else if (x1>x2){
                return NSOrderedDescending;
            } else {
                return NSOrderedSame;
            }
        }
    }];

    [objects release];
    NSLog(@"%@",currentQuery);


    for(int i=0; i<[orderedRes count]; i++){
        NSArray* currObj = [orderedRes objectAtIndex:i];

        SearchResult* searchRes = [[SearchResult alloc] initWithChapterIndex:currentChapterIndex pageIndex:([[currObj objectAtIndex:1] intValue]/webView.bounds.size.height) hitIndex:0 neighboringText:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"unescape('%@')", [currObj objectAtIndex:2]]] originatingQuery:currentQuery];
        [results addObject:searchRes];
        NSLog(@"%@",results);

    [searchRes release];
    }


    //Print results

    for(int i=0;i<[results count];i++)
    {
        SearchResult* hit = (SearchResult*)[results objectAtIndex:i];
        NSLog(@"%@",hit.neighboringText);
    }


    [resultsTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    if((currentChapterIndex+1)<[sharedManager.spineArray count]){
        [self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
    } else {
        fvc.searching= NO;
    }


   [[self resultsTableView] reloadData];
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//- (void)dealloc
////{
////    self.resultsTableView = nil;
////    //[results release];
////    //[currentQuery release];
////    [super dealloc];
//}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    resultsTableView=[[UITableView alloc]init];
    [resultsTableView setDelegate:self];
    [resultsTableView setDataSource:self];

    sharedManager=[Mymanager sharedManager];
    // Do any additional setup after loading the view from its nib.
     results = [[NSMutableArray alloc] init];

    self.navigationItem.title=@"Search ";
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Back"
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;

    [[UINavigationBar appearance] setTitleTextAttributes: @{
                                UITextAttributeTextColor: [UIColor whiteColor],
                          UITextAttributeTextShadowColor: [UIColor lightGrayColor],
                         UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
                                     UITextAttributeFont: [UIFont fontWithName:@"Trebuchet MS" size:15.0f]
     }];


    noMatchingSearch=[[NSArray alloc]initWithObjects:@"No Element Found", nil];

    tableOfContents=[[NSMutableArray alloc]init];
    for (id img in search.subviews)
    {
        if ([img isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [img removeFromSuperview];
        }
    }

    tableOfContents=[sharedManager.List copy];

}

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

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

我的搜索结果

"<SearchResult: 0x113482c0>",
"<SearchResult: 0x11348a20>",
"<SearchResult: 0x88c0a50>"

1 个答案:

答案 0 :(得分:0)

问题在于搜索之前搜索方法重新初始化数组,因此在resultArray中返回0,因此表中没有值

- (void) searchString:(NSString*)query{
    self.results = [[NSMutableArray alloc] init];//Here it becomes 0!!
    [resultsTableView reloadData];
    currentQuery=sharedManager.searchQuery;
}

为了使其正确,在执行搜索后,我相信

[self searchString:currentQuery inChapterAtIndex:0];

将值加载到结果数组中,然后重新加载表。

确保

in .h add

<UITableViewDataSource,UITableViewDelegate>

连接数据源和委托[if via nib]