如何在不同的ViewController中搜索TableviewData?

时间:2014-06-17 07:37:53

标签: ios xcode uisearchdisplaycontroller searchbar

我有一个NewsViewController,其中新闻显示表单XML,我的问题是我创建了单独的类,称为SearchVC,我已经添加了搜索栏,在这里我想搜索所有新闻 (来自NewsViewController)。搜索结果应显示在下拉列表中,如果我单击那些搜索结果它应该重定向到NewsDetailsViewController。我不知道如何做到这一点可以帮助我解决这个问题。

这是我的NewsViewController.m

#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
@interface NewsViewController ()
{
    NSString *temString;
    NSMutableString *strTemp;
}

@end

@implementation NewsViewController
@synthesize arrImages;
@synthesize TittleOne;
@synthesize TittleTwo;
@synthesize TittleThree;
@synthesize datepicker;
@synthesize PickerContainer;
@synthesize datepickerTittle;

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

#pragma mark - View Life Cycle
- (void)viewDidLoad
{
   [TittleOne setFont: [UIFont fontWithName:@"GEEast-ExtraBold" size:12]];
    [TittleTwo setFont: [UIFont fontWithName:@"GEEast-ExtraBold" size:10]];
      [TittleThree setFont: [UIFont fontWithName:@"GEEast-ExtraBold" size:10]];
   // [[UIColor redColor] set];
    [datepickerTittle setFont:[UIFont fontWithName:@"GEEast-ExtraBold" size:12]];
   // [datepickerTittle.textColor= [UIColor yellowColor]];


    [super viewDidLoad];
    self.arrTitles =[[NSMutableArray alloc] init];
    self.arrDescription=[[NSMutableArray alloc]init];
    self.arrImages=[[NSMutableArray alloc]init];
    self.arrDate=[[NSMutableArray alloc]init];
    self.arrUrls=[[NSMutableArray alloc]init];
    //[self performSelectorInBackground:@selector(requestingForNews:) withObject:nil];

   // dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
    self.spinnerView.hidden=NO;
        [self makeRequestForNews];
  //  self.spinnerView.stopAnimating;
    //});

    // Do any additional setup after loading the view.
    [self imagedownloader:@"http://www.shura.bh/MediaCenter/News/"];
}
-(void)requestingForNews:(id)sender
{
     [self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
    //downlaod image
        NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
        NSData  *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *image = [UIImage imageWithData:imageData];
        dispatch_async(dispatch_get_main_queue(), ^{

            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
            imageView.image = image;
            [self.view addSubview:imageView];
        });
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma  mark - make request for news
-(void)makeRequestForNews
{

    NSURL *url =[NSURL URLWithString:self.strNewsApi];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
    NSURLResponse *response = NULL;
    NSError *requestError =NULL;
    //Once you have response with you , Capture YOur Responce data using NsData.

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];

    //Convert the respnse Data into Response String.

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    //Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".

    NSError *parserError = NULL;

    //XML parsing

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
    [xmlParser setDelegate:self];
    [xmlParser parse];

//    NSURL *url = [NSURL URLWithString:url];
//    NSData *data = [NSData dataWithContentsOfURL:url];
//    UIImage *image = [UIImage imageWithData:data];

  //NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];

    //once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{


    if ([elementName isEqualToString:@"ShuraNews"])
    {

    }
    if ([elementName isEqualToString:@"PUBLISHINGPAGEIMAGE"])
    {

    }
    strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //temString =string;
    [strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"TITLE"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrTitles addObject:strTemp];
    }
    if ([elementName isEqualToString:@"PUBLISHINGPAGECONTENT"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrDescription addObject:strTemp];
    }
    if ([elementName isEqualToString:@"NEWSARTICLEDATE"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrDate addObject:strTemp];
    }
    if ([elementName isEqualToString:@"PUBLISHINGPAGEIMAGE"])
    {

        NSLog(@"temstring=== %@", strTemp);
        [self.arrImages addObject:strTemp];
    }
    if ([elementName isEqualToString:@"ShuraNews"])
    {
        [self.tblNews reloadData];
       // self.spinnerView.hidden=YES;
    }
    if ([elementName isEqualToString:@"URL"])
    {
        [self.arrUrls addObject:strTemp];
    }

}

#pragma mark - TabeView Datasource//delegate method

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arrTitles count];
//
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//    [dateFormatter setTimeStyle:NSDateFormatterFullStyle];
//    [dateFormatter setDateFormat:@"dd mmm yyyy"];
//    [datepicker sortUsingComparator:^(id dateObje1,id dateObje2)
//     {
//         NSDate *date1 = [dateFormatter dateFromString:[(datepicker) dateObje1 arrDate]];
//         NSDate *date2 = [dateFormatter dateFromString:[(datepicker) dateObje2 arrDate]];
//         return [date2 compare:date1];
//    }
//     ];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setSeparatorInset:UIEdgeInsetsZero];
    static NSString *cellIdentifier=@"cellNews";
    NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        // cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
        cell.backgroundColor=[UIColor clearColor];
        //SDWebImage Code for lazy loader
        [cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"placeholder.gif"]];
    }

    if( [indexPath row] % 2){
        cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);

    }
    else{
        cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
    }

  //selectbackground color start
    UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
    NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
    cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
    cell.lblTitles.font = [UIFont fontWithName:@"GEEast-ExtraBold" size:12];
    cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
    cell.lblDescription.font =[UIFont fontWithName:@"GE SS Unique" size:12];
    cell.lblDate.font=[UIFont fontWithName:@"GE SS Unique" size:12];
    cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
    cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
    cell.lblTitles.textAlignment= NSTextAlignmentRight;
    cell.lblDate.textAlignment = NSTextAlignmentRight;
    cell.lblDescription.textAlignment = NSTextAlignmentRight;
    //cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]];
    cell.imgNews.image=[UIImage imageWithData:data];
    cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
    cell.imgNews.layer.borderWidth = 2.0;
    [PickerContainer setHidden:YES];
    if (!cell.imgNews.image)
    {
        cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
        cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
        cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
        cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
        cell.imgNews.layer.borderWidth = 0;
           }
 return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",
        [self.arrTitles objectAtIndex:indexPath.row]],@"title",[NSString stringWithFormat:@"%@",
        [self.arrImages objectAtIndex:indexPath.row]],@"img",[NSString stringWithFormat:@"%@",
        [self.arrDescription objectAtIndex:indexPath.row]],@"Des",[NSString stringWithFormat:@"%@",[self.arrUrls objectAtIndex:indexPath.row]],@"url", nil];

    [self performSegueWithIdentifier:@"NewsDetailsID" sender:dict];

}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"NewsDetailsID"])
    {
        ((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:@"title"];
         ((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:@"img"];
        ((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:@"Des"];//strUrl
          ((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:@"url"];
    }
}

- (IBAction)backBtnClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


@end

提前致谢。

1 个答案:

答案 0 :(得分:0)

就搜索而言,您必须根据用户输入的关键字在NewsViewController中搜索您的数组,如果返回任何结果,则执行一个segue到您的NewsDetailsViewController这些结果将显示在哪里。要执行NewsDetailsViewController的segue,您可以使用此方法

[self performSegueWithIdentifier:@"segueIdentifier" sender:nil]; 

另一个建议是使用UITableViewController代替Dropdown。原因是它在SDK本身中可用,您可以使用TableView显示更多数据,而Dropdown必须是自定义的。