用xib自定义UITableViewCell

1.文件结构:ide

2.函数

先建立一个xib文件,删除原有的view,添加一个TableViewCell控件。this

3.ModelTableViewController.m文件spa

 1 #import "ModelTableViewController.h"
 2 #import "Cell.h"
 3 
 4 
 5 @interface ModelTableViewController ()
 6 
 7 @end
 8 
 9 @implementation ModelTableViewController
10 
11 static NSString *cellIdentifier = @"Cell";
12 
13 - (id)initWithStyle:(UITableViewStyle)style
14 {
15     self = [super initWithStyle:style];
16     if (self) {
17         // Custom initialization
18     }
19     return self;
20 }
21 
22 - (void)viewDidLoad
23 {
24     [super viewDidLoad];
25 
26     // Uncomment the following line to preserve selection between presentations.
27     // self.clearsSelectionOnViewWillAppear = NO;
28  
29     // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
30     // self.navigationItem.rightBarButtonItem = self.editButtonItem;
31     UINib *nib = [UINib nibWithNibName:@"Cell" bundle:nil];
32     [self.tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
33     
34 }
35 
36 - (void)didReceiveMemoryWarning
37 {
38     [super didReceiveMemoryWarning];
39     // Dispose of any resources that can be recreated.
40 }
41 
42 #pragma mark - Table view data source
43 
44 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
45 {
46     // Return the number of sections.
47     return 1;
48 }
49 
50 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
51 {
52     // Return the number of rows in the section.
53     return 5;
54 }
55 
56 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
57 {
58     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
59     if (cell == nil) {
60         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
61         
62     }
63     
64     // Configure the cell...
65     
66     return cell;
67 }

注意:自定义的cell都须要注册,3d

此处注册Identifier时用xib文件注册code

UINib *nib = [UINib nibWithNibName:@"Cell" bundle:nil];blog

[self.tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];get

若是是自定义的Cell类,那么用这个函数:- (void)registerClass:forCellWithReuseIdentifier:注册。it

这样就能够用了。io

 

在自定义的xib文件中,若是Cell中有其它控件,如:UIButton等,

 

若是想在TableViewController中获取此button,那么不要经过连线Action,这样会出错。

应该经过如下方式:

1.先设置控件的tag值

2.再在datasource函数中取出,设置控件响应函数

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

中添加

UIButton *deleteButton = (UIButton *)[cell viewWithTag:1];

[deleteButton addTarget:self action:@selector(deleteModel:) forControlEvents:UIControlEventTouchUpInside];

这样不会出错。

相关文章
相关标签/搜索