Mason G. Zhwiti
Mason G. Zhwiti

Reputation: 6540

How do I eliminate the margin on the left side of a UITableView, without creating a gap on the right?

I am targeting iOS 7 and 8, and I want to eliminate the margin appearing on the left side of the images in this UITableView below. I would even be willing to accept a solution that only works on iOS 8 if the solution is simple/elegant. (I would just live with the margin on iOS 7 as it dies out).

This is what I would like it to look like:

I have read through many similar questions on Stack Overflow (such as this one), or ones specific to grouped UITableViews (here and here), but cannot seem to get any to work quite right.

For example, if I try to solve the problem using contentInset (a common answer on SO):

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

    self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, -16, self.tableView.contentInset.bottom, self.tableView.contentInset.right);
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 33, 0, 0);
}

Then I end up with the gap on the right side of the tableview:

I get why it's happening, the entire tableview is just shifted over, as seen in the Debug View Hierarchy screen:

However, I've tried adjusting the tableView frame size to compensate, but it never seems to work correctly. Plus this seems hacky; there must be a better way.

For the record, here's my cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // get a cell that we can use]
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoCell" forIndexPath:indexPath];

    cell.textLabel.numberOfLines = 0;

    cell.selectedBackgroundView = selectionColor;

    cell.accessoryView = [[UIImageView alloc] initWithImage:[PTStyleKit imageOfArrow]];

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:[videos objectAtIndex:indexPath.row] attributes:attributes];

    // Set it in our UILabel and we are done!
    [cell.textLabel setAttributedText:attributedText];

    NSString* filename = [filenames objectAtIndex:indexPath.row];
    if (filename == nil)
    {
        filename = cell.textLabel.text;
    }

    UIImage *imageOne = [UIImage imageNamed:[NSString stringWithFormat:@"medium-%@", filename]];
    cell.imageView.image = [UIImage imageWithCGImage:imageOne.CGImage scale:imageOne.size.height/44 orientation:imageOne.imageOrientation];

    return cell;
}

Upvotes: 5

Views: 8380

Answers (6)

eildiz
eildiz

Reputation: 537

You can try;

[cell.textLabel setTranslatesAutoresizingMaskIntoConstraints:false];
[cell.textLabel.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor].active = YES;
[cell.textLabel.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:22].active = YES; 

Upvotes: 0

Igor Vasilev
Igor Vasilev

Reputation: 351

1. On iOS 13

The key is, together with other things, to set cell.contentView.layoutMargins to .zero:

/// view controller
...
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "identifier")
tableView.separatorInset = .zero
tableView.directionalLayoutMargins = .zero
tableView.layoutMargins = .zero
...

/// data source
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "identifier")!
    cell.textLabel?.text = "Text"
    cell.directionalLayoutMargins = .zero
    cell.layoutMargins = .zero
    cell.contentView.directionalLayoutMargins = .zero
    cell.contentView.layoutMargins = .zero
    return cell
}

If you are utilizing UITableViewController, in addition to all the above you also need to apply this:

tableViewController.viewRespectsSystemMinimumLayoutMargins = false

2. On iOS 12 and lower

It seems that there is no way to use layoutMargins etc. to place the standard UITableViewCell.textLabel to zero offset in relation to the table. The easiest and the only way I found is to subclass the cell and override layoutSubviews like this:

class MyCell: UITableViewCell {
    ...
    override func layoutSubviews() {
        super.layoutSubviews()
        let leading = contentView.directionalLayoutMargins.leading
        textLabel?.frame.origin.x = leading
    }
    ...
}

And of course you need the layout margins to be properly set for that to work

Upvotes: 5

Chetan9007
Chetan9007

Reputation: 908

I think I just came up with an easy solution, which I found over stackoverflow, one way to adjust cell margins, add this method in you code

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    cell.preservesSuperviewLayoutMargins = NO;
    [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
    [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

This solves my problem.

Swift 3 and 4

public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
        cell.separatorInset = .zero
    }
    if (cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins))) {
        cell.preservesSuperviewLayoutMargins = false
    }

    if (cell.responds(to: #selector(setter: UIView.layoutMargins))) {
        cell.layoutMargins = UIEdgeInsets.zero
    }
    if tableView.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
        tableView.separatorInset = .zero
    }

}

Upvotes: 2

Ben
Ben

Reputation: 57227

iOS 8+

In your table view:

table.separatorInset = UIEdgeInsets.zero     // or UIEdgeInsetsZero

You may also need:

table.layoutMargins = UIEdgeInsets.zero

Credit to https://stackoverflow.com/a/30640595/385273.

Upvotes: 0

user1122069
user1122069

Reputation: 1817

Set a clear background to your table view and set thecontentInset property.

Code:

tableView.contentInset = UIEdgeInsetsMake(0, -15, 0, 0);
tableView.backgroundColor = [UIColor clearColor];

but increase the width of the table view by 15 pixels by setting the frame.

Upvotes: 5

Mason G. Zhwiti
Mason G. Zhwiti

Reputation: 6540

It appears the only solution I can find is to subclass UITableViewCell, and then override the layout of the imageView and textLabel. While researching this approach I found this related answer. (I guess I didn't realize this whole time I was searching for tableview behavior that was originally in iOS 6.)

My subclass has this one and only overridden method:

- (void)layoutSubviews
{
    [super layoutSubviews];

    // Slide image to the left, eliminating gutter
    self.imageView.frame = CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height);

    // Slide text label to the left, and extend width by additional
    // space gained by eliminating the left-most gutter
    self.textLabel.frame = CGRectMake((self.imageView.frame.origin.x + self.imageView.frame.size.width + 15), 0, self.textLabel.frame.size.width + 15, self.textLabel.frame.size.height);
}

My resulting tableview now looks exactly the way I want:

enter image description here

Upvotes: 4

Related Questions