最近由于项目的需要,需要进行多人开发,为了方便开发,我们决定采用代码加xib的形式进行控制器的创建,于是花了点时间进行研究,写了一个xib创建tableview的小demo。
·首先创建一个新工程
这里不再进行赘述
·接着新建一个继承自UITableView的文件
按住command + N快速打开新建文件列表,选择iOS->Source->Cocoa Touch Class,在subclass一栏中敲入UITableView,修改名字(xibTableView)勾选Also create XIB file选项,这样做能够免去很多麻烦。
·创建一个新的xib文件继承自UITableViewCell
新建过程不再赘述,新建完成后选中那个新建的xib
进入如上图所说的页面,在Identifier一栏里写上tableviewcell的标识,等会复用tableviewcell的时候有用。
·在你刚刚新建的UItableViewCell的那两个文件中写代码
这里直接上代码
在xxxTableViewCell.h文件中
+ (instancetype)initTableViewCell:(UITableView *)tableView andCellIdentify:(NSString *)cellIdentify;//这是一个类方法能供外界调用,传进的参数是tableView 和cell的标识,返回一个任意类型
在xxxTableViewCell.m文件中
+ (instancetype)initTableViewCell:(UITableView *)tableVieW andCellIdentify:(NSString *)cellIdentify{
xxxTableViewCell *cell = [tableVieW dequeueReusableCellWithIdentifier:cellIdentify];
if (cell == nil) {
cell = [[[NSBundle mainBundle]loadNibNamed:cellIdentify owner:nil options:nil]lastObject];
}//由于是从xib中创建,所以调用loadNibName的方法
return cell;
}
在xxxTableView.m文件中
#import "xxxTableViewCell.h"//导入cell头文件
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;//tableview section个数
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;//每个section有多少行
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* cellIdentity = @"xibTableViewCell";//cell的标识
xibTableViewCell* cell = [xibTableViewCell initTableViewCell:tableView andCellIdentify:cellIdentity];//调用初始化方法
cell.nameLabel.text = @"123";
return cell;//返回该cell
}
至此你已经成功创建了一个tableview啦。
用xib创建tableView有个不好的地方是,你无法在所创的xxxTableView中通过拖控件的方式添加一些控件,只能通过代码去自己写。