2014-01-21 33 views
0

我有一个加载RSS源的表视图。我知道如何添加搜索栏,但我不知道如何实际搜索表格视图。我知道如何搜索一个表视图,如果我加载一个数组,但我无法弄清楚如何搜索这个表视图,因为数据来自一个feed。在UITableView中搜索RSS源

这里是我的代码:

#import "GRSStoreViewController.h" 
#import "RSSChannel.h" 
#import "RSSItem.h" 
#import "WebViewController.h" 
#import "DTCustomColoredAccessory.h" 
#import "SVProgressHUD.h" 
#import "TWTSideMenuViewController.h" 
#import "UIImage+ImageEffects.h" 

@implementation GRSStoreViewController 
{ 
    UIActivityIndicatorView *loadingIndicator; 
} 
@synthesize webViewController; 

- (void)viewDidLoad 
{ 
    // UIImage *normalBackground = [UIImage imageNamed:@"MenuBackground.png"]; 
    // UIImage *effectImage = [normalBackground applyDarkEffect]; 
    // UIImageView *blurredBackground = [[UIImageView alloc]init]; 
    // blurredBackground.image = effectImage; 

    UIImageView *background = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"BackgroundBlurredDarkened.png"]]; 

    UIBarButtonItem *openItem = [[UIBarButtonItem alloc] initWithTitle:@"Menu" style:UIBarButtonItemStylePlain target:self action:@selector(openButtonPressed)]; 
    self.navigationItem.leftBarButtonItem = openItem; 

    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]; 
    self.tableView.backgroundColor = [UIColor blackColor]; 
    [self.tableView setBackgroundView:background]; 
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine]; 
    self.title = @"Store"; 

    UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeRight:)]; 
    swipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight; 
    [self.view addGestureRecognizer:swipeRecognizer]; 

    [[SVProgressHUD appearance]setHudBackgroundColor:[UIColor whiteColor]]; 
    [[SVProgressHUD appearance]setHudForegroundColor:[UIColor blackColor]]; 

    [SVProgressHUD showWithStatus:@"Loading"]; 
    // [SVProgressHUD showWithStatus:@"Loading" maskType:SVProgressHUDMaskTypeGradient]; 
} 

- (IBAction)swipeRight:(UIGestureRecognizer *)sender 
{ 
    [self.sideMenuViewController openMenuAnimated:YES completion:nil]; 
} 

- (void)openButtonPressed 
{ 
    [self.sideMenuViewController openMenuAnimated:YES completion:nil]; 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [SVProgressHUD dismiss]; 
} 

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{ 
    NSLog(@"%@ found a %@ element", self, elementName); 
    if ([elementName isEqual:@"channel"]) 
    { 
     // If the parser saw a channel, create new instance, store in our ivar 
     channel = [[RSSChannel alloc]init]; 

     // Give the channel object a pointer back to ourselves for later 
     [channel setParentParserDelegate:self]; 

     // Set the parser's delegate to the channel object 
     [parser setDelegate:channel]; 
    } 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // return 0; 
    NSLog(@"channel items %d", [[channel items]count]); 
    return [[channel items]count]; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 50; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // return nil; 
    // UIImage *normalBackground = [UIImage imageNamed:@"MenuBackground.png"]; 
    // UIImage *effectImage = [normalBackground applyDarkEffect]; 
    // UIImageView *blurredBackground = [[UIImageView alloc]init]; 
    // blurredBackground.image = effectImage; 

    UIImageView *background = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"BackgroundBlurredDarkened.png"]]; 

    tableView.backgroundView = background; 

    // UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1]; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 
     cell.textLabel.font=[UIFont systemFontOfSize:16.0]; 
    } 
    RSSItem *item = [[channel items]objectAtIndex:[indexPath row]]; 

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 
    [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ssZ"]; 
    NSDate *pubDate = [formatter dateFromString:[item date]]; 
    [formatter setDateStyle:NSDateFormatterMediumStyle]; 
    NSString *dateString = [formatter stringFromDate:pubDate]; 
    NSLog(@"Date String: %@", dateString); 

    NSURL *imageLink = [NSURL URLWithString:[item imageURL]]; 
    NSData *data = [NSData dataWithContentsOfURL:imageLink]; 
    UIImage *image = [[UIImage alloc]initWithData:data]; 

    [[cell textLabel]setText:[item title]]; 

    NSLog(@"Date: %@", [item date]); 

    tableView.backgroundColor = [UIColor clearColor]; 
    cell.backgroundColor = [UIColor clearColor]; 
    cell.textLabel.backgroundColor = [UIColor clearColor]; 
    // cell.textLabel.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:20.0]; 
    cell.textLabel.textColor = [UIColor whiteColor]; 
    cell.imageView.image = image; 
    // tableView.backgroundView = blurredBackground; 

    DTCustomColoredAccessory *accessory = [DTCustomColoredAccessory accessoryWithColor:cell.textLabel.textColor]; 
    // accessory.highlightedColor = kfbBlue; 
    cell.accessoryView =accessory; 

    return cell; 
} 

- (void)fetchEntries 
{ 
    // Create a new data container for the stuff that comes back from the service 
    xmlData = [[NSMutableData alloc]init]; 

    // Construct a URL that will ask the service for what you want - 
    // note we can concatenate literal strings together on multiple lines in this way - this results in a single NSString instance 
    NSURL *url = [NSURL URLWithString:@"http://littleheart.bigcartel.com/products.rss"]; 

    // Put that URL into an NSURLRequest 
    NSURLRequest *req = [NSURLRequest requestWithURL:url]; 

    // Create a connection that will exchange this request for data from the URL 
    connection = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES]; 
} 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 

    if (self) 
    { 
     [self fetchEntries]; 
    } 

    return self; 
} 

// This method will be called several times as the data arrives 
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data 
{ 
    // Add the incoming chunk of data to the container we are keeping 
    // The data always comes in the correct order 
    [xmlData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)conn 
{ 
    /* We are just checking to make sure we are getting the XML 
    NSString *xmlCheck = [[NSString alloc]initWithData:xmlData encoding:NSUTF8StringEncoding]; 
    NSLog(@"xmlCheck = %@", xmlCheck);*/ 

    // [loadingIndicator stopAnimating]; 
    [SVProgressHUD dismiss]; 

    // Create the parser object with the data received from the web service 
    NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData]; 

    // Give it a delegate 
    [parser setDelegate:self]; 

    //Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking 
    [parser parse]; 

    // Get rid of the XML data as we no longer need it 
    xmlData = nil; 

    // Reload the table.. for now, the table will be empty 
    [[self tableView]reloadData]; 

    NSLog(@"%@\n %@\n %@\n", channel, [channel title], [channel infoString]); 
} 

- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error 
{ 
    // Release the connection object, we're done with it 
    connection = nil; 

    // Release the xmlData object, we're done with it 
    xmlData = nil; 

    [SVProgressHUD dismiss]; 

    // Grab the description of the error object passed to us 
    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error localizedDescription]]; 

    // Create and show an alert view with this error displayed 
    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [av show]; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]]; 

    // Push the web view controller onto the navigation stack - this implicitly creates the web view controller's view the first time through 
    // [[self navigationController]pushViewController:webViewController animated:YES]; 
    [self.navigationController pushViewController:webViewController animated:YES]; 

    // Grab the selected item 
    RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]]; 

    NSLog(@"Channel Items: %@", [[channel items]objectAtIndex:[indexPath row]]); 

    // Construct a URL with the link string of the item 
    NSURL *url = [NSURL URLWithString:[entry link]]; 

    NSLog(@"Link: %@", [entry link]); 

    // Construct a request object with that URL 
    NSURLRequest *req = [NSURLRequest requestWithURL:url]; 

    NSLog(@"URL: %@", url); 

    // Load the request into the web view 
    [[webViewController webView]loadRequest:req]; 
    webViewController.hackyURL = url; 
    NSLog(@"Request: %@", req); 

    // Set the title of the web view controller's navigation item 
    // [[webViewController navigationItem]setTitle:[entry title]]; 

    NSLog(@"Title: %@", [entry title]); 

    NSLog(@"Pub Date: %@", [entry date]); 

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 

@end 

我已经试过这样的事情,但它不会改变表视图​​。

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar 

{ BOOL itemFound = NO; NSString * searchText = [searchBar text];

for (int i = 0; [[channel items]count] < i; i++) 
{ 
    RSSItem *item = [[channel items]objectAtIndex:i]; 
    // NSMutableArray *searchItems = [[NSMutableArray alloc]init]; 
    NSString *itemTitle = [item title]; 
    NSRange titleRange = [itemTitle rangeOfString:searchText options:NSCaseInsensitiveSearch]; 
    [[channel items]removeAllObjects]; 

    if (titleRange.location != NSNotFound) 
    { 
     itemFound = YES; 
     // [searchItems addObject:item]; 
     // [self.tableView insertRowsAtIndexPaths:searchItems withRowAnimation:YES]; 
     [[channel items]addObject:item]; 
     [self.tableView reloadData]; 
     break; 
    } 
} 

if (itemFound == NO) 
{ 
    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"" message:@"No Matches Found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [av dismissWithClickedButtonIndex:0 animated:YES]; 
    [av show]; 
} 

[searchBar resignFirstResponder]; 

}

回答

1

你不能做表视图搜索,因为它是不可见的屏幕上的电池大多不包含数据(它们被放在一个可重复使用的池)。您必须在您的数据源中进行搜索:

[channel items] 

希望得到这个帮助。

+0

它有帮助,但我不完全确定如何去搜索频道项目和重新加载表视图,只显示结果。 – raginggoat

+0

看看NSPredictate,你可以用谓词过滤数组并将其保存到另一个数组。有几种不同的方式来显示它,例如你可以使用flag(isSearch),如果它是try,你可以在tableView委托方法中使用[chanels item],但是如果它的false使用由谓词返回的数组。 – Greg

+0

看看我试过了。我正在尝试这种方式,因为我在搜索地图注记时做了类似的事情。 – raginggoat