When using a custom cell in a UITableView I am getting a strange table overlap:
Problem
Dizzle , Creating custom cell and using Control at run time as well as from Xib.
1) Create CustomCell in your ViewController either in Xib or Storyboard.
2) Give Identifier for your cell
3) In your cellForRowAtIndexpath data source method of tableview add below code
static NSString *cellId = @"CustomIdenfier";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:firstCellId];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self createCustomCell:cell atIndexPath:indexPath];
}
[self updateCustomCell:cell atIndexPath:indexPath];
return cell;
4) createCustomCell method If you add control in Xib then you don't need this method
-(void)createCustomCell:(CustomCell*)cell atIndexPath:(NSIndexPath*)indexPath{
//Here I am adding custom label run time, you can add
// Any control in Xib and create a reference IBOutlet for it and user here.
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, cell.contentView.frame.size.width-10, 30)];
lblTitle.textColor = [UIColor blackColor];
lblTitle.tag = 1;
[cell.contentView addSubview:lblTitle];
}
5) updateCustomCell method
-(void)updateCustomCell:(CustomCell*)cell atIndexPath:(NSIndexPath*)indexPath{
UILabel *lblTitle = (UILabel*)[cell.contentView viewWithTag:1];
[lblTitle setText:[NSString stringWithFormat:@"%i",indexPath.row]];
}
//Edit 1 If not using Storyboard, then create custom extension of UITableviewCell.
//CustomCell.h
#import
@interface CustomCell : UITableViewCell
@property (strong, nonatomic) UILabel *lblTitle;
@end
//CustomCell.m
#import "CustomCell.h"
@implementation CustomCell
@synthesize lblTitle;
- (void)awakeFromNib {
NSLog(@"imgUrl:%@ txtName:%@",imgUser,txtName);
// Initialization code
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
//Setup your Cell like initialising variables and setting frames of controls
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end