luky
luky

Reputation: 2370

How to indent only UITableViewCell content not the separator?

If I use this code to indent from left, everything is indented (separator + content)

table.contentInset = UIEdgeInsetsMake(0, 20, 0, 0);

Same if I use this:

cell.layoutMargins = UIEdgeInsetsMake(0, 20, 0, 0);

This doesn't help neither, because it doesn't move the image.

cell.indentationLevel = 10;

Upvotes: 0

Views: 497

Answers (1)

Alanc Liu
Alanc Liu

Reputation: 1294

You can use a CustomTableCell to get what you want:

At first, in ViewController:

#import "ViewController.h"
#import "MyTableCell.h"

@interface ViewController ()

@property UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.backgroundColor = [UIColor grayColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
    if (nil == cell) {
        cell = [[MyTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    }
    //Update data for cell

    return cell;
}

@end

This is MyTableCell.h:

#import "MyTableCell.h"

@interface MyTableCell()

@property UIView *containerView;
@property UIView *separationLine;

@end

@implementation MyTableCell

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

    _containerView = [[UIView alloc] init];
    _containerView.backgroundColor = [UIColor redColor];
    [self addSubview:_containerView];

    _separationLine = [[UIView alloc] init];
    _separationLine.backgroundColor = [UIColor blackColor];
    [self addSubview:_separationLine];

    return self;
}

-(void)layoutSubviews{
    _containerView.frame = CGRectMake(20, 0, self.frame.size.width-20, self.frame.size.height-1);
    _separationLine.frame = CGRectMake(10, self.frame.size.height-1, self.frame.size.width-10, 1);
}

@end

And this is the screenshot for the code:

enter image description here

You can modify the code in "layoutSubviews" as your wish.

Hope it can help you.

Upvotes: 1

Related Questions