1

我尝试使用以下代码在 epub 中搜索,它不起作用的原因是 1。表委托方法在启动时执行,因此搜索结果的默认值为 0,所以我在 viewdidload 方法中给出了一个具有 4 个元素的虚拟数组。所以现在tableview 在虚拟数组中仅显示 4 个 thode 元素,当我滚动 tableview 时,它显示正确的搜索结果,但仍然在该搜索结果中仅显示 4 个元素,因为滚动时不执行行数方法。

当我单击搜索按钮时,它将在第一堂课中调用此方法

SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:@"SearchResultsViewController" bundle:nil];
NSString *searchQuery=[search text];
sharedManager=[Mymanager sharedManager];
sharedManager.searchQuery=searchQuery;
// UITextField *textField = [NSString stringWithFormat:@"%@",searchQuery];
// [textField setFont:[UIFont fontWithName:@"BL-Ruthika-Bold" size:15]];
[searchRes searchString:searchQuery];

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

然后它在 searchresult 类中调用以下方法

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

    NSLog(@"%d",[results count]);
    if([results count]>0)
    {
        return [results count];
    }
    else
    {
        return [test count];
    }
}

//executes only at the startup time ,so the value of results always become zero

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

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

    if([results count]>0) {
       // cell.textLabel.adjustsFontSizeToFitWidth = YES;

        hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
        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:13];
        cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];

        cell.detailTextLabel.textColor=[UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
        cell.detailTextLabel.font= [UIFont fontWithName:@"Trebuchet MS" size:10];

        return cell;
    }
    else
    {
        cell.textLabel.text=[test objectAtIndex:indexPath.row];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    sharedManager=[Mymanager sharedManager];
    hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
    sharedManager.searchFlag=YES;
    sharedManager.hitPageNumber=hit.pageIndex;
    sharedManager.hitChapter=hit.chapterIndex;
    sharedManager.hit=hit;
    //    [fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];
    [self.navigationController popViewControllerAnimated:YES];

}

- (void) searchString:(NSString*)query{
           currentQuery=sharedManager.searchQuery;
        [self searchString:currentQuery inChapterAtIndex:0];
        [[self resultsTableView]reloadData];
    }

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

    currentChapterIndex = index;
    sharedManager=[Mymanager sharedManager];
    Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
       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;
        }
    }
}    

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

- (void) webViewDidFinishLoad:(UIWebView*)webView{

    sharedManager=[Mymanager sharedManager];

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

    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:sharedManager.searchQuery];
        [results addObject:searchRes];

        [searchRes release];
    }

         [[self resultsTableView]reloadData];
    //Print results

    for(int i=0;i<[results count];i++)
    {
        hit = (SearchResult*)[results objectAtIndex:i];
    }

    [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)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];
    test=[[NSArray alloc]initWithObjects:@"one",@"one",@"one",@"one",nil];
    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]
     }];

    [self searchString:sharedManager.searchQuery];
    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];
    resultsTableView.delegate=self;
    resultsTableView.dataSource=self;
    // Release any retained subviews of the main view.
    self.resultsTableView = nil;
}

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

2 回答 2

1

当您收到搜索结果电话时

[self.tableView reloadData];

告诉表视图更新自己。我可以看到你已经在上面的大量代码中尝试了很多次。当您准备好搜索结果时,您只需调用一次。此外,请确保您在调用时对表视图的引用是有效的。

此外,如果您在 XIB 文件中创建表格视图,那么您在其中创建viewDidLoad但未显示的第二个(添加为子视图)只会让您感到困惑,并且您正在尝试重新加载错误的表格视图。

如果您仍然有问题,请显示类属性并删除所有与表格视图无关的代码。

于 2013-05-18T07:55:50.873 回答
0
    resultsTableView=[[UITableView alloc]init];

尝试使用带有属性的 resultsTableView,并将其设置为(非原子,强)。

于 2013-05-18T08:46:26.817 回答