对自定义UITableViewCell的理解

自定义UITableViewCell有两种方法:

1.较早版本 子类UITableViewCell   并利用xib构造

2.利用storyboard直接自定义cell

 

 

1.利用xib

设计好自定义的cell并且连接好控件后  有两种方法引用我们自己的cell

 

方法1:

复制代码
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier=@"name";
    BOOL nibsRegistered=NO;
    if (!nibsRegistered) {
        UINib *nib=[UINib nibWithNibName:@"MyCell" bundle:nil];
       [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
        nibsRegistered=YES;
    }
    MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//cell 上的元素初始化代码

return cell;
}
复制代码
 UINib *nib=[UINib nibWithNibName:@"MyCell" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
这两句代码是引用我们自己定义的cell的关键 首先读取我们自己定义的cell的nib文件 再在tableView中注册 此时 我们定义的cell便加入
到了tableView的可重用队列当中了
MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
这句代码从中取出一个事例  然后初始化 并返回给tableView显示


方法2:
复制代码
 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tableCellIdentifier = @"name";
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:tableCellIdentifier];
    
    if(cell == nil){
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"MyCell" owner:self options:nil];
        for(id oneObject in nib){
            if([oneObject isKindOfClass:[MyCell class]]){
                cell = (MyCell *)oneObject;
            }
        }
    }
    //cell初始化。。。
    
    return cell;
}
复制代码


2.利用storyboard自定义cell
利用storyboard自定义cell比较简单 较xib 方法 少了读取xib文件的一步

在storyboard中拖出一个tableViewController后 拖上去一个cell 然后自己设计cell 最后一定要填上identifier
此时cell已经磨人添加到了tableview的 重用队列中了
引用的时候只需
复制代码
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //这个是在storyboard中设置的identifier
    static NSString *tableCellIdentifier = @"name";
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:tableCellIdentifier];
    //cell初始化
    return cell;
}
复制代码

猜你喜欢

转载自huqiji.iteye.com/blog/2248413