草庐IT

ios - UITableview 委托(delegate)方法未执行

coder 2024-01-20 原文

我尝试了以下代码在 epub 中搜索,它不起作用,原因是 1.表委托(delegate)方法在启动时执行,所以搜索结果的默认值为 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];

然后它调用搜索结果类中的以下方法

- (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);
}

最佳答案

当您收到搜索结果电话时

[self.tableView reloadData];

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

此外,如果您在 XIB 文件中创建 TableView ,那么您在 viewDidLoad 中创建但未显示(添加为 subview )的第二个 View 只会让您和您感到困惑正在尝试重新加载错误的 TableView 。

如果仍有问题,请显示类属性并删除所有与 TableView 无关的代码。

关于ios - UITableview 委托(delegate)方法未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621928/

有关ios - UITableview 委托(delegate)方法未执行的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  6. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

随机推荐