使用xib可以灵活的进行UITableViewCell设计。
工程结构 xcode6环境
我们的UITableView 就是显示一个列表 ,列表每个item实体为Guser
@interface GUser : NSObject
@property (strong,nonatomic) NSString *username;
@property (strong,nonatomic) NSString *desc;
@property (strong,nonatomic) NSString *imgname;
+(instancetype)initUserWith:(NSString *)name :(NSString *)desc :(NSString *)icon;
@end
实现非实例化方法
@implementation GUser
+(instancetype)initUserWith:(NSString *)name :(NSString *)desc :(NSString *)icon {
GUser *u = [[GUser alloc] init];
u.username = name;
u.desc = desc;
u.imgname = icon;
return u;
}
@end
创建MyTableViewCell 封装cell数据合成
@interface MyTableViewCell : UITableViewCell
//@property (strong,nonatomic) GUser *user;
+(instancetype)initCellWithUser:(GUser *)u;
@end
实现
+(instancetype)initCellWithUser:(GUser *)u {
MyTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"mytable_cell" owner:nil options:nil] lastObject];
cell.user = u;
cell.username.text = u.username;
cell.desc.text = u.desc;
cell.icon.image = [UIImage imageNamed:u.imgname];
return cell;
}
创建nib文件
ViewControl 代码
#import <UIKit/UIKit.h>
#import "GUser.h"
#import "MyTableViewCell.h"
@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
@property (strong,nonatomic) NSMutableArray *userArray;
@end
实现
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *mytableView;
@end
@implementation ViewController
{
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell01"];
GUser *u = self.userArray[indexPath.row];
if (cell == nil) {
cell = [MyTableViewCell initCellWithUser:u];
}
NSLog(@"mycell is %@",cell);
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.userArray.count;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITableView *tableView = (id)[self.view viewWithTag:100];
tableView.dataSource = self;
tableView.delegate = self;
tableView.rowHeight = 80;
self.userArray = [[NSMutableArray alloc] initWithCapacity:5];
[self.userArray addObject:[GUser initUserWith:@"gaofeng" :@"fix you0" :@"img01.jpg"]];
[self.userArray addObject:[GUser initUserWith:@"gaofeng" :@"fix you1" :@"img01.jpg"]];
[self.userArray addObject:[GUser initUserWith:@"gaofeng" :@"fix you3" :@"img01.jpg"]];
[self.userArray addObject:[GUser initUserWith:@"gaofeng" :@"fix you4" :@"img01.jpg"]];
[self.userArray addObject:[GUser initUserWith:@"gaofeng" :@"fix you5" :@"img01.jpg"]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Done