6

enter image description here

I want to add horizontal padding for my table view cells as the image shows.

I created a subclass of UITableViewCell, whose width was 314 pixels (screen's width is 320), and set its frame in the initWithCoder method:

[self customizeXPosition:self.profileImage];
[self customizeXPosition:self.birthdayLabel];
[self customizeXPosition:self.heightLabel];
[self customizeXPosition:self.weightLabel];

this is my - (void)customizeXPosition:(UIView *)view:

- (void)customizeXPosition:(UIView *)view {
    CGRect tmpRect = view.frame;
    tmpRect.origin.x += 3.0;
    view.frame = tmpRect;
}

The custom cell was smaller than screen, and I moved every element in the cell to right by 3 pixels. I thought this code should achieve my goal, yet it didn't. The view didn't change in the simulator, just like I didn't write any code.

how can I achieve my goal?

Community
  • 1
  • 1
Brian
  • 30,156
  • 15
  • 86
  • 87
  • 1
    check out this link: http://stackoverflow.com/questions/11399402/grouped-uitableview-and-horizontal-margins – faterpig Oct 29 '13 at 03:59
  • awesome! this link solved my problem! would you like to organize the info and answer this question? – Brian Oct 29 '13 at 05:48

3 Answers3

6

Try overriding the -setFrame method in UITableViewCell as per this post :

How to set the width of a cell in a UITableView in grouped style

Swift version

Community
  • 1
  • 1
faterpig
  • 344
  • 1
  • 6
  • btw @Brian, I think it'll be better to just make this the answer but go over to that SO page and up the user's answer. I won't want to take credit for the perfect answer he gave. He helped me too! :) and for others who saw this answer please if that answer helped you, up vote his answer and not me. :) – faterpig Oct 29 '13 at 07:29
3

@faterpig is correct in many situations. However, setting frame may break auto layout.

If your auto layout is broken due to setting frame, you can add a UIView ,which has shorter width than the cell contentView, to the contentView and put your other UI elements on the view.

By doing the following settings, you can get cells with "horizontal padding":

cell.backgroundColor = UIColor.clearColor()
cell.contentView.backgroundColor = UIColor.clearColor()
Brian
  • 30,156
  • 15
  • 86
  • 87
2

This works well for padding things in views:

yourView.layer.sublayerTransform = CATransform3DMakeTranslation(10, 0, 0);

dev-null
  • 27
  • 2