jueves, 8 de octubre de 2015

iOS: Custom TableViewCell

CustomViewController.h

@interface CustomViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

...
@property(weak, nonatomic) IBOutlet UITableView* tableView;


@end


CustomViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

   ...
    
    UINib *cellNib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil];
    [[self tableView] registerNib:cellNib forCellReuseIdentifier:@"Cell"];
    
    UINib *sectionNib = [UINib nibWithNibName:@"CustomTableViewHeaderFooterView" bundle:nil];
    [[self tableView] registerNib:sectionNib forCellReuseIdentifier:@"Section"];

}

...

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"Cell";
    
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[CustomTableViewHeaderFooterView allocinitWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    
   // Do something with the cell
   ...
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return ROW_HEIGHT;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CustomTableViewHeaderFooterView *cell = [tableView dequeueReusableCellWithIdentifier:@"Section"];
    
    if (cell == nil) {
        cell = [[CustomTableViewHeaderFooterView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Section"];
    }

...
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;

}

CustomTableViewCell.h

@interface EJRecommendationsTableViewCell : UITableViewCell

// Properties

@end

CustomTableViewCell.m

@implementation EJRecommendationsTableViewCell

- (void)awakeFromNib {
    // Initialization code
}

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

    // Configure the view for the selected state
}

@end

Note:

1) Link the TableView outlet to the TableView view. 
2) Create a .xib and named it "CustomTableViewCell.xib" in IdentityInspector set the class to "CustomTableViewCell". The top most view of this view has to be a UITableViewCell.
3) "CustomTableViewHeaderFooterView" is identical to "CustomTableViewCell".

No hay comentarios:

Publicar un comentario