UITableView自定义单元格

时间:2023-01-27 10:53:26

随手笔记:

RootViewController代码

 

#import "RootViewController.h"

#import "AddressContact.h"

#import "Student.h"

#import "StuInfoViewController.h"

#import "NewViewController.h"

#import "POAPinyin.h"

#import "TableViewCellLeft.h"

#import "TableViewCellRight.h"

@interface RootViewController ()

{

    AddressContact * addresscontact;

    NSMutableArray * totaldata;

    NSMutableArray * keys;

}

@end

 

@implementation RootViewController

-(void)dealloc

{

   // [addresscontact.dictionary release];

    [keys release];

    [totaldata release];

    [super dealloc];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

       

    }

    return self;

}

-(void)add:(UIBarButtonItem *)barbtn

{

    NewViewController * newvc=[[NewViewController alloc]init];

    

     newvc.newdelegate=self;

    

    CATransition *animation = [CATransition animation];

    [animation setDuration:3];

    // [animation setType: kCATransitionMoveIn];

    [animation setType:@"rippleEffect"];

    //[animation setSubtype: kCATransitionFromTop];

    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];

    [self.navigationController.view.layer addAnimation:animation forKey:nil];

    

    [self.navigationController pushViewController:newvc animated:YES];

    [newvc release];

}

-(void)method:(NSString *)name sex:(NSString *)sex phone:(NSString *)phone hobby:(NSString *)hobby photo:(NSString *)photo

{

    BOOL b=[name isEqualToString:@""];

    BOOL c=name==nil;

    if (!c&&!b) {

        NSString * yingwenname=[POAPinyin convert:name];

        char c=[yingwenname characterAtIndex:0];

        NSString * firstchar=[NSString stringWithFormat:@"%c",c];

        if (![keys containsObject:firstchar]) {

            [keys addObject:firstchar];

            keys=[[NSMutableArray alloc]initWithArray:[keys sortedArrayUsingSelector:@selector(compare:)]];

            NSMutableArray * muary=[[NSMutableArray alloc]initWithCapacity:10];

            [addresscontact.dictionary setObject:muary forKey:firstchar];

        }

        NSMutableArray * array=[addresscontact.dictionary objectForKey:firstchar];

//        for (int i=0; i<[totaldata count]; i++) {

//             NSMutableArray *array1= [totaldata objectAtIndex:i];

//            Student * stu=[array1 objectAtIndex:0];

//            if ([[POAPinyin convert:stu.name] isEqualToString:firstchar]) {

//                array=array1;

//                break;

//            }

//        }

       

        [array retain];

        Student * stu=[[Student alloc]init];

        [stu setValue:name forKey:@"name"];

        [stu setValue:sex forKey:@"sex"];

        [stu setValue:phone forKey:@"phone"];

        [stu setValue:hobby forKey:@"hobby"];

        [stu setValue:photo forKey:@"photo"];

        [array addObject:stu];

        [stu release];

         

    }

}

- (void)viewDidLoad

{

    [super viewDidLoad];

 

    //self.navigationItem.rightBarButtonItem=self.editButtonItem;

    UIBarButtonItem * barbutton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];

    NSArray * ary=[[NSArray alloc]initWithObjects:self.editButtonItem,barbutton, nil];

    self.navigationItem.rightBarButtonItems=ary;

    self.navigationItem.title=@"23班通讯录";

    UITableView * tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStyleGrouped];

    //tableview.backgroundColor=[UIColor blueColor];

   

    tableview.separatorColor=[UIColor redColor];

    tableview.dataSource=self;

    tableview.delegate=self;

    

    [self.view addSubview:tableview];

    [tableview release];

    addresscontact=[AddressContact SharedAddressContact];

   //[addresscontact retain];

    [addresscontact.dictionary retain];

   // keys=[[NSMutableArray alloc]initWithArray:[addresscontact.dictionary allKeys]];

    NSString * path=[[NSBundle mainBundle]pathForResource:@"students" ofType:@"plist"];

    NSMutableArray * array=[[NSMutableArray alloc]initWithContentsOfFile:path];

    for (int i=0; i<[array count]; i++) {

        NSDictionary *dictionary=array[i];

        Student * stu= [[Student alloc]init];

          [stu setValuesForKeysWithDictionary:dictionary];

        

        NSString * firstchar=[NSString stringWithFormat:@"%c",[[POAPinyin convert:stu.name] characterAtIndex:0]];

        NSMutableArray * grouparray=[addresscontact.dictionary objectForKey:firstchar];

        if (grouparray==nil) {

            grouparray=[[NSMutableArray alloc]initWithCapacity:10];

            [addresscontact.dictionary setObject:grouparray forKey:firstchar];

        }

        [grouparray addObject:stu];

    }

    

    

    NSMutableArray * arry=[[NSMutableArray alloc]initWithArray:[addresscontact.dictionary allKeys]];

     keys= [[NSMutableArray alloc] initWithArray:[arry sortedArrayUsingSelector:@selector(compare:)]];

    

//    totaldata=[[NSMutableArray alloc]initWithCapacity:26];

//    for (int i=0; i<26; i++) {

//        char key=(char)(i +65);

//        NSString * k=[NSString stringWithFormat:@"%c",key];

//        NSMutableArray * mary=[addresscontact.dictionary objectForKey:k];

//        [totaldata addObject:mary];

//    }

    //keys=[[NSMutableArray alloc]initWithCapacity:26];

   //   NSMutableArray * arry=[NSMutableArray arrayWithArray:[addresscontact.dictionary allKeys]];

    //    keys= [NSMutableArray arrayWithArray:[arry sortedArrayUsingSelector:@selector(compare:)]];

     //[addresscontact retain];

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    

    [[[self.view subviews]objectAtIndex:0] reloadData];

    // targetIndexPathForMoveFromRowAtIndexPath: toProposedIndexPath:<#(NSIndexPath *)#>

}

#pragma mark - 添加或修改

-(void)setEditing:(BOOL)editing animated:(BOOL)animated

{

    [super setEditing:editing animated:animated];

    UITableView *tableview=[[(UITableView *)self.view subviews]objectAtIndex:0];

    [tableview setEditing:!tableview.editing animated:animated];

}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    //UITableViewCell * cell= [tableView cellForRowAtIndexPath:indexPath];

//    if ([cell.textLabel.text isEqualToString:@"(空)"]) {

//        return NO;

//    }

    return YES;

}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return UITableViewCellEditingStyleDelete;

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    [tableView beginUpdates];

    NSString * s= keys[indexPath.section];

    

    if (editingStyle==UITableViewCellEditingStyleDelete) {

        NSMutableArray * array=[addresscontact.dictionary objectForKey:s];

        if ([array count]>1) {

            [array removeObjectAtIndex:indexPath.row];

            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

        }

        else

        {

             //[array removeObjectAtIndex:indexPath.row];

            [keys removeObjectAtIndex:indexPath.section];

           [addresscontact.dictionary removeObjectForKey:s];

            //[totaldata removeObjectAtIndex:indexPath.section];

            //NSLog(@"%d",indexPath.section);

            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];

            //[tableView reloadData];

        }

    }

    

    

    [tableView endUpdates];

}

#pragma mark - 移动

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}

 

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath

{

  

    //[tableView beginUpdates];

   // char c=(char)(sourceIndexPath.section+65);

    NSString * s=[keys objectAtIndex:sourceIndexPath.section];

    NSMutableArray *array=[addresscontact.dictionary objectForKey:s];

    Student * stu=[array objectAtIndex:sourceIndexPath.row];

    [stu retain];

    [array removeObjectAtIndex:sourceIndexPath.row];

    [array insertObject:stu atIndex:destinationIndexPath.row];

    [stu release];

    

    //[tableView endUpdates];

}

 

-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath

{

    if (sourceIndexPath.section!=proposedDestinationIndexPath.section) {

        return sourceIndexPath;

    }

    return proposedDestinationIndexPath;

}

 

#pragma mark - 选中cell

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{//标记

    StuInfoViewController * info = [[StuInfoViewController alloc]init];

    int selection = indexPath.section;//cell.tag/1000;

    int row = indexPath.row;//cell.tag%1000;

    

    NSString *sec = keys[selection];

    NSMutableArray * ary = [addresscontact.dictionary objectForKey:sec];

    info.student = ary[row];

    

    

    

    [self.navigationController pushViewController:info animated:NO];

   // UITableViewCell *cell=(UITableViewCell *)tap.view;

    

    

    CATransition *animation = [CATransition animation];

    [animation setDuration:3];

    // [animation setType: kCATransitionMoveIn];

    [animation setType: @"pageCurl"];

    //[animation setSubtype: kCATransitionFromTop];

    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];

    [self.navigationController.view.layer addAnimation:animation forKey:nil];

    

    [info release];

 

}

#pragma mark - 行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    //A  65

//    char key=(char)(section +65);

//    NSString * k=[NSString stringWithFormat:@"%c",key];

//    NSMutableArray *array= [addresscontact.dictionary objectForKey:k];

//    while (array==nil) {

//        key=key+1;

//          k=[NSString stringWithFormat:@"%c",key];

//        array= [addresscontact.dictionary objectForKey:k];

//    }

//    

//    if ([array count]==0) {

//        return 1;

//    }

    NSString * s=keys[section];

    NSMutableArray * array=[addresscontact.dictionary objectForKey:s];

    return [array count];

}

#pragma mark - 返回单元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

   // NSLog(@"%d",indexPath.section);

//    char key=(char)(indexPath.section +65);

//    NSString * k=keys[indexPath.section];

//    NSMutableArray *array=[addresscontact.dictionary objectForKey:k];

//    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"aaa"];

//    if (cell==nil) {

//        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"aaa"]autorelease];

//        UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapclick:)];

//        //[cell addGestureRecognizer:tap];

//        [tap release];

//    }

//    if ([array count]>0) {//[array objectAtIndex:0]!=nil

//        cell.userInteractionEnabled=YES;

//        Student * stu= array[indexPath.row];

//       // cell.textLabel.multipleTouchEnabled=YES;

//        cell.textLabel.text=stu.name; //[stu.name stringByAppendingString:[NSString stringWithFormat:@"\n%@",stu.sex ]];

//        cell.detailTextLabel.text=stu.sex;

//        //cell.tag=indexPath.section*1000+indexPath.row;

//        

//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

//       

//        return cell ;

//    }

//    else

//    {

//        cell.userInteractionEnabled=NO;

//        cell.textLabel.text=@"(空)";

//        cell.detailTextLabel.text=@"";

//        //cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 0, 0);

//        //UITableViewCell *cell1=[[UITableViewCell alloc]init];

//         return cell;

//        

//    }

//    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];

//    button.backgroundColor= [UIColor redColor];

//    cell.accessoryView= button;

    

    

    NSString * key=keys[indexPath.section];

     NSMutableArray *array=[addresscontact.dictionary objectForKey:key];

    

    Student *stu=array[indexPath.row];

    if ([stu.sex isEqualToString:@"男"])

    {

        static NSString *identifier=@"cell1";

        TableViewCellLeft *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

        if (cell==nil) {

            

            cell=[[[TableViewCellLeft alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier]autorelease];

        }

        cell.stu=array[indexPath.row];

        return cell;

    }

    else

    {

        static NSString * identifier=@"cell2";

        TableViewCellRight * cell=[tableView dequeueReusableCellWithIdentifier:identifier];

        if (cell==nil) {

            cell=[[[TableViewCellRight alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier]autorelease];

        }

        cell.stu=array[indexPath.row];

        return cell;

    }

 

}

#pragma mark - 块标题

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    return keys[section];

}

//#pragma mark - 块foot

//- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

//{

//    return keys[section];

//}

-(void)tapclick:(UITapGestureRecognizer*)tap

{

    //标记

    StuInfoViewController * info=[[StuInfoViewController alloc]init];

    [self.navigationController pushViewController:info animated:NO];

    UITableViewCell *cell=(UITableViewCell *)tap.view;

    int selection=cell.tag/1000;

    int row=cell.tag%1000;

    char c=selection+65;

    NSString *sec=[NSString stringWithFormat:@"%c",c];

    NSMutableArray * ary= [addresscontact.dictionary objectForKey:sec];

    info.student=ary[row];

    

    CATransition *animation = [CATransition animation];

    [animation setDuration:1];

    // [animation setType: kCATransitionMoveIn];

    [animation setType:@"pageCurl"];

    //[animation setSubtype: kCATransitionFromTop];

    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];

    [self.navigationController.view.layer addAnimation:animation forKey:nil];

    

    [info release];

}

//右边的key

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

{

//    NSArray * ary=[addresscontact.dictionary allKeys];

//    NSArray * ay= [ary sortedArrayUsingSelector:@selector(compare:)];

 

    return keys;

}

#pragma mark - 块数量

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return [addresscontact.dictionary count];

}

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString * key=keys[indexPath.section];

    NSMutableArray *array=[addresscontact.dictionary objectForKey:key];

    Student * stu=array[indexPath.row];

    CGRect r= [stu.hobby boundingRectWithSize:CGSizeMake(220, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName, nil]context:nil];

    

    return 90+CGRectGetHeight(r);

}

/*

#pragma mark - Navigation

 

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

 

@end

 

自定义cell:

@implementation TableViewCellLeft

 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        // Initialization code

        self.backgroundColor=[UIColor yellowColor];

        self.imageview=[[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)]autorelease];

        self.namelabel=[[[UILabel alloc]initWithFrame:CGRectMake(60, 0, 100, 30)]autorelease];

       // self.namelabel.backgroundColor=[UIColor redColor];

        self.sexlabel=[[[UILabel alloc]initWithFrame:CGRectMake(60, 30, 100, 30)]autorelease];

       // self.sexlabel.backgroundColor=[UIColor orangeColor];

        self.phonelabel=[[[UILabel alloc]initWithFrame:CGRectMake(60, 60, 130, 30)]autorelease];

        self.hobbylabel=[[[UILabel alloc]initWithFrame:CGRectMake(60, 90, 100, 30)]autorelease];

        //self.hobbylabel.backgroundColor=[UIColor purpleColor];

        self.hobbylabel.font=[UIFont systemFontOfSize:15];

        self.hobbylabel.numberOfLines=0;

        

        [self.contentView addSubview: self.imageview];

        [self.contentView addSubview: self.namelabel];

        [self.contentView addSubview: self.sexlabel];

        [self.contentView addSubview: self.phonelabel];

        [self.contentView addSubview: self.hobbylabel];

    }

    return self;

}

-(void)setStu:(Student *)stu

{

    self.namelabel.text=stu.name;

    self.sexlabel.text=stu.sex;

    self.phonelabel.text=stu.phone;

    

    self.imageview.image=[UIImage imageNamed:stu.photo];

    

    

    CGRect r= [stu.hobby boundingRectWithSize:CGSizeMake(220, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.hobbylabel.font,NSFontAttributeName, nil]context:nil];

    self.hobbylabel.frame=CGRectMake(60, 90,220, CGRectGetHeight(r));

    self.hobbylabel.text=stu.hobby;

    

}

- (void)awakeFromNib

{

    // Initialization code

}

 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated

{

    [super setSelected:selected animated:animated];

 

    // Configure the view for the selected state

}

 

@end