您的位置:首页 > 产品设计 > UI/UE

[IOS]用自定义的cell来创建UITableView

2013-08-20 10:49 513 查看
步骤:

1.创建自定义的CellView.xib,操作New File->User Interface->View->命名cellView

2.往上面拖放一个UITableViewCell,然后向其中拖放添加UILabel,UITextField,UIButton,如下图:



3.创建一个类Cell,操作New File->Cocoa Touch->Objective-C class->Class:Cell,Subclass of:UITableViewCell

4.将cellView.xib中的Cell的class设置为Cell类,然后可以将label关联到Cell.h中,也可以设置Label的Tag属性为1,后面有两种方法调用xib文件,一种是通过tag,其次就是通过cell。注意:xib文件中的File's Owner只能关联到viewController,这里自定义的cell.xib没有可以关联的contrller文件,所以不需要写,只需要把xib中的cell控件关联到cell类就可以了

5.ViewController.h:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDataSource>
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@property(retain,nonatomic)NSArray *arr;
@end6.ViewController.m:
#import "ViewController.h"
#import "Cell.h"

static NSString *strIdentifier = @"strIdentifier";
@interface ViewController ()

@end

@implementation ViewController

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

- (void)viewDidLoad
{
[super viewDidLoad];
self.arr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
//获得包含tableViewcell的nib文件
UINib *nib = [UINib nibWithNibName:@"cellView" bundle:nil];
//用这个nib文件注册成tableView中表示为strIdentifier的cell
[self.tableView registerNib:nib forCellReuseIdentifier:strIdentifier];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arr count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//询问是否有未使用的,表示为strIdentifier的cell,如果没有,并且tableview注册过,系统会建一个新的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];
//用这个自定义的cell可以用绑定的方式修改内容,要将自定义的cell.xib的class修改成Cell类
((Cell *)cell).label.text = [self.arr objectAtIndex:[indexPath row]];

//也可以用tag的方式查找到需要修改的view
//((UILabel *)[cell viewWithTag:1]).text = [self.arr objectAtIndex:[indexPath row]];
return cell;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)dealloc {
[_tableView release];
[self.arr release];
[super dealloc];
}
@end
运行结果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: