2016-07-08 9 views
-1

я следующий код в viewdidloadКак Impliment панель поиска в режиме Таблица для контактов в ИО

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 *[email protected]"ContactDetails"; 

NSDictionary *contactsDisplayDetails1 [email protected]{@"IND_ID":indid}; 

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

код implimenting Строка поиска

{ 


    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]; 

код для просмотра таблицы

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; 

Как я могу реализовать панель поиска в виде таблицы для контактов в панели рассказов? Я новичок в iOS ? и как реализовать кнопку кнопки и точек в виде таблицы?

+0

проверить это http://www.appcoda.com/ios-contacts -framework/это может помочь вам – sanman

+0

Devi Я разместил здесь весь код. Вы можете использовать. Я реализовал панель поиска с помощью методов-делегатов. Если вы ищете имя (keta, anna, a, n, john, j, h ..... и т. Д.), Он показывает вам результат. Ответ на результат лучше, чем предоставление ссылки. – user3182143

ответ

3

Devi мой полный answer.It работы perfectly.I использовать поиск bar.Also использовать что методы делегата.

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" 
) 
+0

Где вы вызывали делегата панели поиска, я. searchbarContacts.delegate = self; С вызовом делегата, как вызовет забастовка в поисковой строке. В моем примере моя панель поиска в uitableview, как вызвать этот делегат в классе таблицы ... – iOS

0

См. Ниже ссылку, я могу реализовать панель поиска в виде таблицы, используя это.

 Смежные вопросы

  • Нет связанных вопросов^_^