iOS OC TableView的使用(3)-用xib自定义Ce

2018-09-03  本文已影响545人  CSDN_georgeChen

写在前面

实现方法

1、构造一个自己需要的TableView中的Cell的样式,我们先新建Grouper.xib、Grouper.h、Grouper.m文件。

.h文件:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface GrouperCell : UITableViewCell//该类继承于UITableViewCell

@property (retain,nonatomic) IBOutlet UILabel * lbl_name;
@property (retain,nonatomic) IBOutlet UILabel * lbl_ID;
@property (retain,nonatomic) IBOutlet UILabel * lbl_gender;
@property (retain,nonatomic) IBOutlet UIImageView * lbl_headPortrait;

@end

.m文件:

#import "GrouperCell.h"

@implementation GrouperCell

@synthesize lbl_ID,lbl_name,lbl_gender;

-(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self)
    {
        
    }
    return self;
}

-(void) setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

@end

.xib 文件

和在StoryBoard中一样使用控件构造样式,并与上面的类文件建立IBOutlet联系。

DIYCell.png

并设置该xib类:

DIYCell2.png

2、 在调用的ViewController中

#import "GrouperCell.h"

代理方法内:

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellTableIndentifier = @"Group_Cell";
    //单元格ID
    //重用单元格
    GrouperCell * cell = [tableView dequeueReusableCellWithIdentifier:CellTableIndentifier];
    //初始化单元格
    if(cell == nil)
    {
        NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@"GrouperCell" owner:self options:nil];
        //xib文件
        cell = [nib objectAtIndex:0];
    }
    
    cell.lbl_name.text = [(User *)[arr_groupers objectAtIndex:indexPath.row] userName];
    cell.lbl_ID.text = [(User *)[arr_groupers objectAtIndex:indexPath.row] userID];
    if([[(User *)[arr_groupers objectAtIndex:indexPath.row] gender] isEqualToString:@"f"])
    {
        cell.lbl_gender.text = @"女";
        cell.imageView.image = [UIImage imageNamed:@"default_portrait_f"];
    }
    else
    {
        cell.lbl_gender.text = @"男";
        cell.imageView.image = [UIImage imageNamed:@"default_portrait_m"];
    }
    
    return cell;
}

让数组中存储的实体类信息展示在label上就完成了。

上一篇 下一篇

猜你喜欢

热点阅读