How to set margin for uitableviewcell

How to set a marker UITableViewCellprogrammatically without creating a whole new user cell?

+5
source share
5 answers

You need to subclass UITableViewCelland override the method layoutSubviews:

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect tmpFrame = self.imageView.frame;
    tmpFrame.origin.x += 10;
    self.imageView.frame = tmpFrame;

    tmpFrame = self.textLabel.frame;
    tmpFrame.origin.x += 10;
    self.textLabel.frame = tmpFrame;

    tmpFrame = self.detailTextLabel.frame;
    tmpFrame.origin.x += 10;
    self.detailTextLabel.frame = tmpFrame;
}
+16
source

Wouldn't it be better to make UITableViewCell higher than for a start? If you content is always 100 pixels high, just make a 110px cell to get extra space of 10 pixels, no special sockets are needed :)

+2
source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

, . , .

+1

To set the left margin, you can use:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:       (NSIndexPath *)indexPath
{
    return 1;
}
+1
source

Andrey has a good solution, but if you use an accessory, you need this code:

const int MARGIN = 16; // Left and right margin

- (void)layoutSubviews {
    [super layoutSubviews];

    /* Add left margin to the image and both labels */
    CGRect frame = self.imageView.frame;
    frame.origin.x += MARGIN;
    self.imageView.frame = frame;

    frame = self.textLabel.frame;
    frame.origin.x += MARGIN;
    frame.size.width -= 2 * MARGIN;
    self.textLabel.frame = frame;

    frame = self.detailTextLabel.frame;
    frame.origin.x += MARGIN;
    frame.size.width -= 2 * MARGIN;
    self.detailTextLabel.frame = frame;

    /* Add right margin to the accesory view */
    if (self.accessoryType != UITableViewCellAccessoryNone) {
        float estimatedAccesoryX = MAX(self.textLabel.frame.origin.x + self.textLabel.frame.size.width, self.detailTextLabel.frame.origin.x + self.detailTextLabel.frame.size.width);

        for (UIView *subview in self.subviews) {
            if (subview != self.textLabel &&
                subview != self.detailTextLabel &&
                subview != self.backgroundView &&
                subview != self.contentView &&
                subview != self.selectedBackgroundView &&
                subview != self.imageView &&
                subview.frame.origin.x > estimatedAccesoryX) {

                // This subview should be the accessory, change its frame
                frame = subview.frame;
                frame.origin.x -= MARGIN;
                subview.frame = frame;
                break;
           }
        }
    }
}

There is no easy way to handle the accessory. I have been looking for a while, and this is the best solution I've seen so far.

+1
source

All Articles