實現(xiàn)一個類似通訊錄有searchbar和索引功能的UITableview

2017-07-04 16_40_08.gif

主界面代碼:

#import "ViewController.h"
#import "CountryCodeViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super  viewDidLoad];
    UILabel *codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 50, 25)];
    self.label = codeLabel;
    codeLabel.font = [UIFont systemFontOfSize:17];
    codeLabel.textColor = [UIColor colorWithRed:0 green:255 blue:127 alpha:0.7];
    codeLabel.text = @"+86";
    [self.view addSubview:codeLabel];
    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    codeBtn.frame = CGRectMake(100, 100, 50, 25);
    [codeBtn addTarget:self action:@selector(chooseCountryCode) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:codeBtn];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)chooseCountryCode{
    CountryCodeViewController *CCVC = [[CountryCodeViewController alloc] init];
    CCVC.selectBlock = ^(NSDictionary *dic) {
    self.label.text = [NSString stringWithFormat:@"+%@",dic[@"country_code"]];
    };
    [self.navigationController pushViewController:CCVC animated:YES];
}
@end

cell代碼

#import <UIKit/UIKit.h>
@interface CountryCodeCell : UITableViewCell
@property(nonatomic,strong)UILabel* CountryLable;
@property(nonatomic,strong)UILabel* CodeLable;
@property(nonatomic,strong)NSDictionary* CountryDic;
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
@end

#import "CountryCodeCell.h"
@implementation CountryCodeCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _CountryLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 100, 
self.contentView.bounds.size.height)];
    _CountryLable.font = [UIFont systemFontOfSize:15];
    [self.contentView addSubview:_CountryLable];
    _CodeLable = [[UILabel alloc] initWithFrame:CGRectMake(self.contentView.bounds.size.width-20, 5, 50, self.contentView.bounds.size.height)];
    _CodeLable.font = [UIFont systemFontOfSize:15];
    [self.contentView addSubview:_CodeLable];
}
    return self;
}
-(void)setCountryDic:(NSDictionary *)CountryDic{
    _CountryDic = CountryDic;
    self.CountryLable.text = _CountryDic[@"country"];
    self.CodeLable.text = [NSString stringWithFormat:@"+%@",_CountryDic[@"country_code"]];   
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}
@end

TableView數(shù)據(jù)源格式

image.png

選擇界面TableView代碼

#import <UIKit/UIKit.h>
@interface CountryCodeViewController : UIViewController
@property (copy,nonatomic) void (^selectBlock)(NSDictionary*);
@end


#define kScreen_Width [UIScreen mainScreen].bounds.size.width
#import "CountryCodeViewController.h"
#import "CountryCodeCell.h"

@interface CountryCodeViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UISearchBar *searchBar;
@property (strong, nonatomic) NSDictionary *countryCodeListDict, *searchResults;
@property (strong, nonatomic) NSMutableArray *indexList;
@end

@implementation CountryCodeViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"選擇國家或地區(qū)";
_tableView = ({
    UITableView *tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableview.delegate = self;
    tableview.dataSource = self;
    [tableview registerClass:[CountryCodeCell class] forCellReuseIdentifier:@"codeCell"];
    [self.view  addSubview:tableview];
    tableview;
});
_searchBar = ({
    UISearchBar *searchbar = [UISearchBar new];
    searchbar.delegate = self;
    searchbar.placeholder = @"國家/地區(qū)名稱";
    [searchbar sizeToFit];
    searchbar;
});
self.tableView.tableHeaderView = _searchBar;
[self initData];
}

- (void)initData{
  NSString *path = [[NSBundle mainBundle] pathForResource:@"country" ofType:@"plist"];
  self.countryCodeListDict = self.searchResults = [NSDictionary dictionaryWithContentsOfFile:path];
  [self initIndexList];
}
- (void)initIndexList{
self.indexList = [self.searchResults.allKeys mutableCopy];

[_indexList sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    if ([obj1 isEqualToString:@"#"]) {
        return NSOrderedAscending;
    }else if([obj2 isEqualToString:@"#"]){
        return NSOrderedDescending;
    }else{
        return [obj1 compare:obj2];
    }
}];
[_indexList insertObject:UITableViewIndexSearch atIndex:0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - tableview delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  return self.indexList.count -1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  return [self.searchResults[self.indexList[section+1]] count];
}
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
  return self.indexList;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
  return index >0? index-1: index;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  return 20;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *headView = [UIView new];
headView.backgroundColor = [UIColor colorWithRed:240/255.0 green:255/255.0 blue:255/255.0 alpha:1];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 40, 10)];
titleLabel.font = [UIFont systemFontOfSize:12];
titleLabel.text = [self.indexList[section+1] isEqualToString:@"#"]? @"常用": self.indexList[section+1];
[headView addSubview:titleLabel];
return headView;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CountryCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"codeCell" forIndexPath:indexPath];
cell.CountryDic = self.searchResults[self.indexList[indexPath.section+1]][indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (_selectBlock) {
    _selectBlock(_searchResults[_indexList[indexPath.section+ 1]][indexPath.row]);
}
[self.navigationController popViewControllerAnimated:YES];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
cell.separatorInset = UIEdgeInsetsMake(0, 15, 0, (kScreen_Width - cell.contentView.bounds.size.width) + 15);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView == self.tableView) {
    [self.searchBar resignFirstResponder];
}
}

#pragma mark - searchBar delegate

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSMutableDictionary *searchResults = @{}.mutableCopy;
NSString *strippedStr = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *searchItems = [strippedStr componentsSeparatedByString:@" "];
if (strippedStr.length==0) {
    searchResults = self.countryCodeListDict.mutableCopy;
}else{
    NSMutableArray *andMatchPredicates = [NSMutableArray new];
    for (NSString *searchString in searchItems) {
        NSMutableArray *searchItemsPredicate = [NSMutableArray new];
        NSExpression *lex = [NSExpression expressionForKeyPath:@"country"];
        NSExpression *rex = [NSExpression expressionForConstantValue:searchString];
        NSPredicate *finalPredicate = [NSComparisonPredicate predicateWithLeftExpression:lex rightExpression:rex modifier:NSDirectPredicateModifier type:NSContainsPredicateOperatorType options:NSCaseInsensitivePredicateOption];
        [searchItemsPredicate addObject:finalPredicate];
        
        lex = [NSExpression expressionForKeyPath:@"country_code"];
        rex = [NSExpression expressionForConstantValue:searchString];
        finalPredicate = [NSComparisonPredicate predicateWithLeftExpression:lex rightExpression:rex modifier:NSDirectPredicateModifier type:NSContainsPredicateOperatorType options:NSCaseInsensitivePredicateOption];
        [searchItemsPredicate addObject:finalPredicate];
        
        lex = [NSExpression expressionForKeyPath:@"iso_code"];
        rex = [NSExpression expressionForConstantValue:searchString];
        finalPredicate = [NSComparisonPredicate predicateWithLeftExpression:lex rightExpression:rex modifier:NSDirectPredicateModifier type:NSContainsPredicateOperatorType options:NSCaseInsensitivePredicateOption];
        [searchItemsPredicate addObject:finalPredicate];
        
        NSCompoundPredicate *orMatchPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:searchItemsPredicate];
        [andMatchPredicates addObject:orMatchPredicate];
    }
    NSCompoundPredicate *finalCompoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:andMatchPredicates];
    for (NSString *key in [self.countryCodeListDict allKeys]) {
        NSArray *finalList = [self.countryCodeListDict[key] filteredArrayUsingPredicate:finalCompoundPredicate];
        if (finalList.count>0) {
            [searchResults setValue:finalList forKey:key];
        }else{
            [searchResults removeObjectForKey:key];
        }
    }
    self.searchResults = searchResults;
    [self initIndexList];
    [self.tableView reloadData];
} 
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末瓷胧,一起剝皮案震驚了整個濱河市背传,隨后出現(xiàn)的幾起案子囊陡,更是在濱河造成了極大的恐慌,老刑警劉巖群发,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件凤覆,死亡現(xiàn)場離奇詭異链瓦,居然都是意外死亡,警方通過查閱死者的電腦和手機盯桦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門慈俯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拥峦,你說我怎么就攤上這事贴膘。” “怎么了略号?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵刑峡,是天一觀的道長。 經(jīng)常有香客問我玄柠,道長突梦,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任羽利,我火速辦了婚禮宫患,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铐伴。我一直安慰自己,他們只是感情好俏讹,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布当宴。 她就那樣靜靜地躺著,像睡著了一般泽疆。 火紅的嫁衣襯著肌膚如雪户矢。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天殉疼,我揣著相機與錄音梯浪,去河邊找鬼捌年。 笑死,一個胖子當(dāng)著我的面吹牛挂洛,可吹牛的內(nèi)容都是我干的礼预。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼虏劲,長吁一口氣:“原來是場噩夢啊……” “哼托酸!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起柒巫,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤励堡,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后堡掏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體应结,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年泉唁,在試婚紗的時候發(fā)現(xiàn)自己被綠了鹅龄。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡游两,死狀恐怖砾层,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贱案,我是刑警寧澤肛炮,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站宝踪,受9級特大地震影響侨糟,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜瘩燥,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一秕重、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧厉膀,春花似錦溶耘、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至企软,卻和暖如春庐扫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工形庭, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留铅辞,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓萨醒,卻偏偏與公主長得像斟珊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子验靡,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容