如何将UISearchBar添加到此?

时间:2013-06-20 09:10:30

标签: iphone ios objective-c ipad uisearchbar

我想在下面的代码中添加UISearchBar,我在Xcode 4.6中使用。 有人可以帮助我吗?

// 

#import "SocialMasterViewController.h"

#import "SocialDetailViewController.h"

@interface SocialMasterViewController () {
    NSXMLParser *parser;
    NSMutableArray *feeds;
    NSMutableDictionary *item;
    NSMutableString *title;
    NSMutableString *link;
    NSString *element;
    NSArray *filteredStrings;
}
@end

@implementation SocialMasterViewController



-(void)gotosharing {
    UIStoryboard *sharingStoryboard = [UIStoryboard storyboardWithName:@"Sharing" bundle:nil];
    UIViewController *initialSharingVC = [sharingStoryboard instantiateInitialViewController];
    initialSharingVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    [self presentViewController:initialSharingVC animated:YES completion:nil];
     }


- (void)awakeFromNib
{
    [super awakeFromNib];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    feeds = [[NSMutableArray alloc] init];
    NSURL *url = [NSURL URLWithString:@"http://www.rssmix.com/u/3735817/rss.xml"
            ];
    parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:self];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];

    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];

}

- (void)refresh:(UIRefreshControl *)refreshControl {
    [refreshControl endRefreshing];
}


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

#pragma mark - Table View

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return feeds.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey: @"title"];
    return cell;




}

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

    element = elementName;

    if ([element isEqualToString:@"item"]) {

        item    = [[NSMutableDictionary alloc] init];
        title   = [[NSMutableString alloc] init];
        link    = [[NSMutableString alloc] init];

    }

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

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

        [item setObject:title forKey:@"title"];
        [item setObject:link forKey:@"link"];

        [feeds addObject:[item copy]];

    }

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if ([element isEqualToString:@"title"]) {
        [title appendString:string];
    } else if ([element isEqualToString:@"link"]) {
        [link appendString:string];
    }

}

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

    [self.tableView reloadData];

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showDetail"]) {

        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSString *string = [feeds[indexPath.row] objectForKey: @"link"];
        [[segue destinationViewController] setUrl:string];

    }
}






- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self filterURLsWithSearchBar:searchText];
    [self.tableView reloadData];
}

- (void)filterURLsWithSearchBar:(NSString *)searchText
{
    //[filteredStrings removeAllObjects];
    for (NSString *rssUrl in feeds)
    {
        NSComparisonResult result = [rssUrl compare:searchText
                                            options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
                                              range:[rssUrl rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]];
        if (result == NSOrderedSame) {
            [self->feeds addObject:filteredStrings];
        }
    }
}

@end

基本上,我希望将NSXMLParser引入的搜索字词的结果过滤到搜索栏中。

任何帮助都非常感谢你们/ gals。

3 个答案:

答案 0 :(得分:0)

这样做

  • 将来自解析器的值get存储到数组中。 responseArray
  • 使用另一个数组存储要在表格中显示的值 datasourceArray
  • webvservice收到成功回复datasourceArray=responseArray后,使用[tableView reloadData]重新加载表
  • 搜索开始时,从responseArray搜索将结果加载到DatasourceArray,然后再次致电reloadData

答案 1 :(得分:0)

您可以使用uitextFeild的textFeildDidBegunEditing委托方法

然后此代码将帮助您过滤

    NSMutableArray  *array1=(NSMutableArray*)[txtEditFavoriteColor.text componentsSeparatedByString:@" "];//words from textFeild

      for (NSString *str in array1) 
        {
            NSString *tempStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if([tempStr length])
            {
                [arryOfWordsToBeSearched addObject:tempStr]; 

            }
        }



        NSMutableArray *subpredicates = [NSMutableArray array];

        for(NSString *term in arryOfWordsToBeSearched) {
            NSPredicate *p = [NSPredicate predicateWithFormat:@"name contains[cd] %@",term];
            [subpredicates addObject:p];
        }

        NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
//***************************************************************predicate made above******
        result = [[NSMutableArray alloc]initWithArray:[arryOfDummyData filteredArrayUsingPredicate: filter]];//search on data array using predicate

答案 2 :(得分:0)

使用nibfile创建表视图控制器子类。在表视图顶部的nibfile中添加搜索栏。然后将自动添加搜索结果视图控制器。  searchResultViewController的大部分属性如delegate,searchBar,searchDisplayDatasource和delegate都是自动设置的。并且对于搜索栏,委托也被设置为文件所有者。

现在实现表视图符合此协议。 。

实施以下委托方法。

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
// create the array of ur search result object
}

现在实现tableViewDataSource并委托检查哪个表正在调用方法 如下

if (tableView == self.searchDisplayController.searchResultsTableView)
{
    // searchResultsTableView
}
else
{
    // main table view
}

实现相应的代码。