ios - 如何在 iOS 的联系人 TableView 中实现搜索栏

标签 ios objective-c uitableview xcode6 searchbar

<分区>


想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .

关闭 6 年前

我在 viewdidload 中有以下代码

totalstring=[[NSMutableArray alloc]initWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"n",@"o",@"p",@"q",@"r",@"s",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z", nil];





indid=indidvalue1;

NSLog(@"the ind id value is %@",indid);

serviceCall=[[Services alloc]init];

NSString *contactsDisplay1=@"ContactDetails";

NSDictionary *contactsDisplayDetails1 =@{@"IND_ID":indid};

[serviceCall ContactsDisplayUrl:contactsDisplay1 ContactsDisplayDetails:contactsDisplayDetails1];
[serviceCall setDelegate:self];

实现搜索栏的代码

{


    filteredstring =[[NSMutableArray alloc]init];

    for (NSString *str in totalstring )
    {

     NSRange stringrange =[str rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if(stringrange.location!= NSNotFound)
        {
            [filteredstring addObject:str];
        }
    }
}
[tableView reloadData];

TableView 代码

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
    cell.textLabel.text = [searchResultsArray objectAtIndex:indexPath.row];
} else
{
    UIFont *myfont=[UIFont fontWithName:@"Arial" size:35];
    cell.textLabel.text = [contactNameSplitDisplayArray objectAtIndex:indexPath.row];
    cell.detailTextLabel.text=[relationTypeSplitDisplayArray objectAtIndex:indexPath.row];
    cell.textLabel.font=myfont;
}
return cell;

我如何在 Storyboard中的联系人的 TableView 中实现搜索栏?我是 iOS 新手 ? 以及如何在表格 View 中实现加号按钮和点号按钮?

最佳答案

Devi 我的完整答案。它完美地工作。我使用搜索栏。还使用该委托(delegate)方法。

ViewController.h

#import <UIKit/UIKit.h>
#import <Contacts/Contacts.h> //Must import contact framework 

@interface ViewController :  UIViewController<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UISearchBar *searchbarContacts;
@property (strong, nonatomic) IBOutlet UITableView *tableViewContactData;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
{
  NSMutableArray *arrayTableData;
  NSMutableArray *arraySearchContactData;
}

@end

@implementation ViewController

@synthesize tableViewContactData;

@synthesize searchbarContacts;


- (void)viewDidLoad 
{
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
  arrayTableData = [[NSMutableArray alloc]init];
  arraySearchContactData = [[NSMutableArray alloc]init];
  [self fetchContactsandAuthorization];
  [tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
  [self.view addSubview:tableViewContactData];
}

//Fetching Contact and Authorization access

-(void)fetchContactsandAuthorization
{
  // Request authorization to Contacts
  CNContactStore *store = [[CNContactStore alloc] init];
  [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted == YES) {
        //keys with fetching properties
        NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
        NSString *containerId = store.defaultContainerIdentifier;
        NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
        NSError *error;
        NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
        if (error) {
            NSLog(@"error fetching contacts %@", error);
        } else {
            NSString *phone;
            NSString *fullName;
            NSString *firstName;
            NSString *lastName;
            UIImage *profileImage;
            NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
            for (CNContact *contact in cnContacts)
            {
                // copy data to my custom Contacts class.
                firstName = contact.givenName;
                lastName = contact.familyName;
                if (lastName == nil) {
                    fullName=[NSString stringWithFormat:@"%@",firstName];
                }else if (firstName == nil){
                    fullName=[NSString stringWithFormat:@"%@",lastName];
                }
                else{
                    fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
                }
                UIImage *image = [UIImage imageWithData:contact.imageData];
                if (image != nil) {
                    profileImage = image;
                }else{
                    profileImage = [UIImage imageNamed:@"person-icon.png"];
                }
                for (CNLabeledValue *label in contact.phoneNumbers)
                {
                    phone = [label.value stringValue];
                    if ([phone length] > 0) {
                        [contactNumbersArray addObject:phone];
                    }
                }
                NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage,@"userImage",phone,@"PhoneNumbers", nil];
                [arrayTableData addObject:[NSString stringWithFormat:@"%@",[personDict objectForKey:@"fullName"]]];
                [arraySearchContactData addObject:[NSString stringWithFormat:@"%@",[personDict objectForKey:@"fullName"]]];
                NSLog(@"The contactsArray are - %@",arrayTableData);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [tableViewContactData reloadData];
            });
        }
    }
}];
}

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


#pragma mark - UITableView Data Source Methods

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

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static  NSString *strCell = @"cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
   if(cell==nil)
   {
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
   }
   cell.textLabel.text = arrayTableData[indexPath.row];
   return cell;
}

#pragma mark - SearchBar Delegate Methods

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
  @try
  {
    [arrayTableData removeAllObjects];
    stringSearch = @"YES";
    NSString *name = @"";
    if ([searchText length] > 0)
    {
        for (int i = 0; i < [arraySearchContactData count] ; i++)
        {
            name = [arraySearchContactData objectAtIndex:i];
            if (name.length >= searchText.length)
            {
                NSRange titleResultsRange = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if (titleResultsRange.length > 0)
                {
                    [arrayTableData addObject:[arraySearchContactData objectAtIndex:i]];
                }
            }
        }
    }
    else
    {
        [arrayTableData addObjectsFromArray:arraySearchContactData];
    }
    [tableViewContactData reloadData];
}
@catch (NSException *exception) {
}
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)SearchBar
{
  SearchBar.showsCancelButton=YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)theSearchBar
{
  [theSearchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)SearchBar
{
  @try
  {
    SearchBar.showsCancelButton=NO;
    [SearchBar resignFirstResponder];
    [tableViewContactData reloadData];
  }
  @catch (NSException *exception) {
  }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)SearchBar
{
  [SearchBar resignFirstResponder];
}

@end

联系人的打印结果

The contactsArray are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
)

关于ios - 如何在 iOS 的联系人 TableView 中实现搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38261248/

上一篇:ios - 如果我希望它在整个应用程序生命周期内都存在,是否需要手动删除观察者?

下一篇:android - 在单个应用程序中接收某些应用程序的所有通知(Android 和 IOS)

相关文章:

ios - UISearchBar 在导航栏下方的动画不正确

ios - 可将表格菜单扩展到 Xcode 中的新 View Controller

ios - 限制某些 View 的自动旋转

iphone - 每个对象有多个委托(delegate)?

objective-c - 什么时候在 Objective-C 中使用原语?

iphone - 以编程方式创建音频数据

iPhone 重置桌面 View

来自小键盘的 iOS 9/Swift 2 输入找不到键盘

ios -[NSArray componentsJoinedByString] 有条件

objective-c - subview 显示在父 UIView 的边界之外