用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];

這樣不會出錯。

相關文章
相關標籤/搜索