如何设置uitableviewcell的边距



如何在不创建全新自定义单元格的情况下以编程方式设置UITableViewCell的边距?

您需要将UITableViewCell子类化并覆盖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;
}

让UITableViewCell比一开始的内容更高不是更有意义吗?如果你的内容总是100px高,只需将单元格设置为110px即可获得所需的额外10px空间,无需自定义单元格:(

要设置左边距,可以使用:

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

Andrey有一个很好的解决方案,但如果您使用附件视图,则需要以下代码:

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;
           }
        }
    }
}

处理附件视图没有简单的方法。我已经寻找了一段时间,这是迄今为止我看到的最好的解决方案。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

此方法将返回单元格,您可以在其中配置单元格。只需设置控件的框架,将它们移动到计算位置即可。

最新更新