标签:
UITableViewCell:自定义的单元格,可以在xib中创建单元格,也可以在storyBorad中创建单元格。有四种创建方式
1 #import <Foundation/Foundation.h> 2 3 @interface Contact : NSObject 4 @property (copy,nonatomic)NSString *name; 5 @property (copy,nonatomic)NSString *faceName; 6 -(instancetype)initWithName:(NSString*)name andFaceName:(NSString*) faceName; 7 @end
1 #import "Contact.h" 2 3 @implementation Contact 4 -(instancetype)initWithName:(NSString*)name andFaceName:(NSString*) faceName 5 { 6 self = [super init]; 7 if(self) 8 { 9 _name = [name copy]; 10 _faceName = [faceName copy]; 11 } 12 return self; 13 } 14 @end
在试图控制器中完成代码:
1 #import "ViewController.h" 2 #import "Contact.h" 3 @interface ViewController ()<UITableViewDataSource> 4 @property (weak, nonatomic) IBOutlet UITableView *tableView; 5 @property (strong,nonatomic)NSMutableArray *contacts; 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 //初始化数据 13 self.contacts = [NSMutableArray arrayWithCapacity:9]; 14 for(int i=0; i<9; i++) 15 { 16 Contact *conatct = [[Contact alloc]initWithName:[NSString stringWithFormat:@"name%d",i+1] andFaceName:[NSString stringWithFormat:@"%d.png",i]]; 17 [self.contacts addObject:conatct]; 18 } 19 20 //设置tableView的数据源 21 self.tableView.dataSource = self; 22 } 23 24 #pragma mark -tableView的数据源方法 25 //每一组多少行 26 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 27 { 28 return self.contacts.count; 29 } 30 //设置每一个单元格的内容 31 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 32 { 33 //1.根据reuseIdentifier,先到对象池中去找重用的单元格对象 34 static NSString *reuseIdentifier = @"myCell"; 35 UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; 36 //2.设置单元格对象的内容 37 Contact *contact = [self.contacts objectAtIndex:indexPath.row]; 38 UILabel *label = (UILabel*)[cell viewWithTag:1]; 39 label.text = contact.name; 40 UIImageView *imageView = (UIImageView*)[cell viewWithTag:2]; 41 [imageView setImage:[UIImage imageNamed:contact.faceName]]; 42 return cell; 43 } 44 45 @end
Objective-C:UITableViewCell自定义单元格
标签:
原文地址:http://www.cnblogs.com/XYQ-208910/p/4790600.html