用xib自定义UITableViewCell
1.文件结构:
2.
先创建一个xib文件,删除原有的view,添加一个TableViewCell控件。
3.ModelTableViewController.m文件
#import "ModelTableViewController.h"
#import "Cell.h" @interface ModelTableViewController () @end @implementation ModelTableViewController static NSString *cellIdentifier = @"Cell"; - (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
} - (void)viewDidLoad
{
[super viewDidLoad]; // Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
UINib *nib = [UINib nibWithNibName:@"Cell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:cellIdentifier]; } - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return ;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return ;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } // Configure the cell... return cell;
}
注意:自定义的cell都需要注册,
此处注册Identifier时用xib文件注册
UINib *nib = [UINib nibWithNibName:@"Cell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
如果是自定义的Cell类,那么用这个函数:- (void)registerClass:forCellWithReuseIdentifier:注册。
这样就可以用了。
在自定义的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];
这样不会出错。
最新文章
- Url和Uri的区别
- JS &;&; JSON
- ThinkCmfX模板常量
- Selenium2学习-042-Selenium3启动Firefox Version 48.x浏览器(ff 原生 geckodriver 诞生)
- java 小记
- jQuery Mobile 页面事件总结
- K - 4 Values whose Sum is 0(中途相遇法)
- 【Java基础】Java异常的一些总结
- [Mugeda HTML5技术教程之6]添加元素
- 转:Reddit排名算法工作原理
- sqlserver中数据的四种插入方式
- Django学习(二)---使用模板Templates
- Eclipse Maven Mybatis的使用
- 安装sql server2017出现错误:Visual Studio 运行时";Microsoft visual c++2017 X64 Minimum Runtime - 14.10.25008";需要修复
- python之路-列表、元组、range
- Flask web开发之路八
- Py-numpy的随机函数【转载】
- JS 对应CSS 样式
- WebGL——osg框架学习三
- ospf基础理论