UITableview 数据 [英] UITableview Data

查看:19
本文介绍了UITableview 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个应用程序,我必须在其中读取 ABAddressBook 中的联系人.我已读取数据并将其存储在 dictionary 中.我想显示名称每个部分按字母顺序排列.dictionary 中的每个对象都指向一个人的详细信息.有什么帮助吗?

I am making an application in which I have to read the contacts from an ABAddressBook. I have read the data and stored it in a dictionary.I want to display the names alphabetically in every section. Each object in the dictionary refers to the details of a single person. Any help ?

(
        {
        letter = D;
        name = zzzz;
        telephone = "1234566";
    },
        {
        letter = R;
        name = "ffff";
        telephone = "332333";
    },
        {
        letter = A;
        name = aaaaa;
        telephone = "1112226";
    },
        {
        letter = s;
        name = ssssss;
        telephone = "234 56792";
    },
        {
        letter = K;
        name = "Klll";
        telephone = "(888) 888-8888";
    }

)

推荐答案

我正在发送代码,我已经完成了此类任务.实际上您的问题是您无法对字典进行排序.

I am sending code, I have done already this type of task. Actually your problem you not able sort dictictionary.

请参考我的代码.

#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import "AddressBookUI/AddressBookUI.h"

@interface AddressBookViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,ABNewPersonViewControllerDelegate>
{
    IBOutlet UITableView* addressNameView;
    ABAddressBookRef _addressBook;
}

@property(nonatomic,retain)UITableView* addressNameView;
@property (nonatomic, retain) NSMutableArray *contacts;
@property (nonatomic, retain)IBOutlet UILabel *titleText;
@property(nonatomic,retain)IBOutlet UISegmentedControl *segmentControl;

-(IBAction)backAction:(id)sender;

@end

/****************/

/****************/

#import "AddressBookViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AddressEntryDetailController.h"
#import "MenuViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h> 

NSInteger static compareViewsByOrigin(id sp1, id sp2, void *context)
{
    // UISegmentedControl segments use UISegment objects (private API). Then we can safely
    //   cast them to UIView objects.
    float v1 = ((UIView *)sp1).frame.origin.x;
    float v2 = ((UIView *)sp2).frame.origin.x;
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

@implementation AddressBookViewController

@synthesize addressNameView,contacts;
@synthesize titleText,segmentControl;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didChangeSegmentControl:(UISegmentedControl *)control 
{
    int index=control.selectedSegmentIndex;
    NSLog(@"Slected Index : %d",index);
    if(index==1)
    {
        [self getAllContacts];
    }
    else
    {
        [self getAllContactsByRelevence];    
    }
}


-(void)getAllContacts
{

    ABRecordRef source = ABAddressBookCopyDefaultSource(_addressBook); 
    NSArray *tempArray = (NSArray *)(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(_addressBook, source, kABPersonSortByFirstName));

    [contacts removeAllObjects];
    if ([tempArray count] > 0) 
    {
        [contacts addObjectsFromArray:tempArray];
    } 
    [addressNameView reloadData];
    titleText.text=@"All";

}

-(void)getAllContactsByRelevence
{
    ABRecordRef source = ABAddressBookCopyDefaultSource(_addressBook); 
    NSArray *tempArray = (NSArray *)(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(_addressBook, source, kABPersonSortByLastName));
    [contacts removeAllObjects];
    if ([tempArray count] > 0) 
    {
        [contacts addObjectsFromArray:tempArray];
    } 
    [addressNameView reloadData];
    titleText.text=@"All";
}


- (void)viewDidLoad
{
    _addressBook = ABAddressBookCreate();
    contacts=[[NSMutableArray alloc]init];
    [self getAllContacts];
    addressNameView.layer.borderWidth=2;
    addressNameView.layer.cornerRadius=13;
    addressNameView.layer.borderColor =[UIColor colorWithRed:192.0f/255.0f green:189.0f/255.0f blue:189.0f/255.0f alpha:1.0f].CGColor;
    addressNameView.backgroundColor=[UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:235.0f/255.0f alpha:1.0f];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self CreateAlphabetButton];

    self.segmentControl.selectedSegmentIndex=1;
    [self.segmentControl addTarget:self action:@selector(didChangeSegmentControl:) forControlEvents:UIControlEventValueChanged];

}

-(void)CreateAlphabetButton
{
    int yPoint=110;
    NSString *list=@"*ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for(int y=1;y<=27;y++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(720,yPoint,50,28);
        yPoint+=29;
        button.titleLabel.text=[list substringWithRange:NSMakeRange(y-1, 1)];
        UILabel *readding=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 30)];
        readding.text=[list substringWithRange:NSMakeRange(y-1, 1)];
        readding.textColor=[UIColor darkTextColor];
        [readding setTextAlignment:UITextAlignmentCenter];
        readding.font=[UIFont boldSystemFontOfSize:20.0];
        readding.backgroundColor = [UIColor clearColor];
        [button addSubview:readding];

        [button addTarget:self action:@selector(toggleOpen:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [self.view bringSubviewToFront:button];
    }
}

-(IBAction)toggleOpen:(id)sender
{
    UIButton *btn=(UIButton*)sender;
    NSLog(@"%@",btn.titleLabel.text);
    //for searching
    if([btn.titleLabel.text isEqualToString:@"*"])
    {
        [self getAllContacts]; 
        titleText.text=@"All";
    }
    else
    {
        NSArray *tempArray = (NSArray *)(ABAddressBookCopyPeopleWithName(_addressBook,(CFStringRef)btn.titleLabel.text));
        [contacts removeAllObjects];
        if ([tempArray count] > 0) 
        {
            [contacts addObjectsFromArray:tempArray];
        } 
        [addressNameView reloadData];
        titleText.text=btn.titleLabel.text;  
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(IBAction)backAction:(id)sender
{
    //MenuViewController *menuView=[[MenuViewController alloc]initWithNibName:@"MenuViewController" bundle:[NSBundle mainBundle]];
    //[self presentModalViewController:menuView animated:YES];
    [self dismissModalViewControllerAnimated:YES];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([self.contacts count]==0)
        return 1;
    return [self.contacts count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   
    static NSString *CellIdentifier = @"TableViewCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];       
    }
    cell.tag = indexPath.row;

    if([self.contacts count]>0)
    {

    NSObject *object = [self.contacts objectAtIndex:indexPath.row];
    NSString *firstName=[(NSString *)ABRecordCopyValue((ABRecordRef)object, kABPersonFirstNameProperty) autorelease];
    NSString *lastName =[(NSString *)ABRecordCopyValue((ABRecordRef)object, kABPersonLastNameProperty) autorelease];
    if(lastName)
        cell.textLabel.text=[NSString stringWithFormat:@"%@  %@",firstName,lastName];
    else
        cell.textLabel.text=firstName;
    }
    else
    {
        cell.textLabel.text=@"No Contacts";
    }
    //UISwipeGestureRecognizer* gestureR;
    //gestureR = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)] autorelease];
   // gestureR.direction = UISwipeGestureRecognizerDirectionLeft;
   // [cell addGestureRecognizer:gestureR];
   // cell.editing=YES;

    return cell;
}



- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.contacts count]>0)
    return UITableViewCellEditingStyleDelete;
    else
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        NSLog(@"Delete Clicked on cell Index : %d",indexPath.row);
        // Commit the delete
        ABRecordRef* personObject=(ABRecordRef*) [self.contacts objectAtIndex:indexPath.row];
        if(ABAddressBookRemoveRecord(_addressBook, personObject, NULL))
        {
        ABAddressBookSave(_addressBook, NULL);
        [self getAllContacts];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                            message:@"Contact succesfully deleted" 
                                                           delegate:self cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
    }
}


/*
 - (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer
{    
    NSLog(@"%d = %d",recognizer.direction,recognizer.state);
}
*/

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

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.contacts count]>0)
    {
    AddressEntryDetailController *entryDetail=[[AddressEntryDetailController alloc]initWithNibName:@"AddressEntryDetailController" bundle:[NSBundle mainBundle]];
    int index=indexPath.row;
    entryDetail.personObject=(ABRecordRef*) [self.contacts objectAtIndex:index];
    entryDetail._addressBook=&_addressBook;
    entryDetail.addressBookViewController=self;
    [self presentModalViewController:entryDetail animated:YES];
    }
}


-(IBAction)addToAddressbook:(id)sender
{  
    ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
    picker.newPersonViewDelegate = self;

    UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picker];
    [self presentModalViewController:navigation animated:YES];

    [picker release];
    [navigation release];

   /* ABPeoplePickerNavigationController *picker =
    [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentModalViewController:picker animated:YES];*/

}

#pragma mark ABNewPersonViewControllerDelegate methods
// Dismisses the new-person view controller. 
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person
{
    [self dismissModalViewControllerAnimated:YES];
    [self getAllContacts];
}

这篇关于UITableview 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆