[BS-13] 创建和注册UITableViewCell及Storyboard和Xib区别

 

创建和注册UITableViewCell及Storyboard和Xib区别

// 界面创建完成被调用
- (void)viewDidLoad
{
    [super viewDidLoad];
    /**
     如果采用如下3种方式,为tableView注册了原形Cell,系统会用注册的cell作为显示用的cell和可重用cell,一旦缓冲区中不存在可重用cell,系统会使用注册的原形Cell新实例化一个Cell供程序使用!
     因此只要注册了原形Cell,创建cell时就不再需要cell == nil的判断了。
     */

    //1.纯代码自定义的cell注册如下:
    [self.tableView registerClass:[HMStatusCell class] forCellReuseIdentifier:ID];

    //2. 使用Xib自定义的cell,注册如下
     [self.tableView registerNib:[UINib nibWithNibName:@"WZUserCell" bundle:nil] forCellReuseIdentifier:UserCellId];
    
    //3. 使用Storyboard创建ProtoCell,只需设置ProtoCell的reuseIdentifier,系统自动注册。
    
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  
    return self.statusFrames.count;
}

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

    // 官方建议使用以下方法,此方法要求必须预先注册可重用单元格,否则崩溃!程序发布前的崩溃,可帮助发现问题。
    HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    //HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 一旦在注册了可重用Cell,以上两个方法是等价的

    //if (cell == nil) {
    //    cell = [[HMStatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    //} //注册了原型cell,就不需要再创建了,直接出列使用即可。

    return cell;
}

 

Storyboard和Xib中显示的TableView有较大的区别:

Storyboard中可以放置各种导航/TabBar/视图控制器(场景scene),可以设置各个界面之间的关系,属于重量级的IB工具。

而Xib一般用来设置比较小的局部的UI,如用来自定义某个TableView的cell/footerView/headerView等。另外即使将UITableViewController拖入Xib,也不能在其中添加ProtoCell或普通的cell,强行拖入立即报错(error: Illegal Configuration: Table views with embedded sections and cells are only supported in storyboard documents)。另外拖入Xib中的UIViewController似乎都不能Embed in导航控制器。

Storyboard(UITableViewController)如下图:

Xib(UITableView)如下图:

 

posted @ 2016-05-06 18:57  stevenwuzheng  阅读(5808)  评论(0编辑  收藏  举报