ios - UITableview cellForRowAtIndexPath 方法没有执行?

标签 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>"

最佳答案

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

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

为了使它正确,执行搜索后,我相信
[self searchString:currentQuery inChapterAtIndex:0];

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

确保

在 .h 添加
<UITableViewDataSource,UITableViewDelegate>

在 Nib

连接数据源和委托(delegate)[如果通过 nib]

关于ios - UITableview cellForRowAtIndexPath 方法没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16580329/

相关文章:

ios - 如何在 iPhone 模拟器上重置 Twitter 访问权限

ios - 允许同时创建多少个 AVPlayer?

objective-c - 返回类型应该是什么?

ios - UITableViewCell subview 在选择时消失(但此 subview 中的内容可见)

ios - 无效更新: invalid number of rows in section 0 when trying to expand and collapse UITableView sections

ios - 体系结构i386的 undefined symbol :用于OpenCV项目

iphone - 在 iPhone 应用程序中从谷歌驱动器下载图像

objective-c - 查找未使用的图像或覆盖 +imageNamed : to log images not found

objective-c - 是否可以在实例化对象之前检查 Storyboard中是否存在标识符?

iphone - 同步访问 UITableViewDelegate 逻辑