-->

Custom UITableViewCell subview layout

2020-07-27 02:58发布

问题:

I'm creating a custom UITableViewCell, similar in style to UITableViewCellStyleValue1 but with an editable text field on the right side instead of the detailTextLabel. I'm a little confused on how to size the edit field properly. I want to take the length of the textLabel into account, as well as the size of the contentView, and be able to do the Right Thing when its table view is in edit mode, or if an accessory view (like a disclosure arrow) is added.

But the width of the contentView seems to always be 320 (on iPhone in portrait mode) even for a grouped table. Within my UITableViewCell subclass, I see no way to get access to the table view to which it belongs so I can get the style of the table and adjust the margins accordingly.

I figure I can handle this in a custom fashion in the tableView's delegate -tableView:willDisplayCell:forRowAtIndexPath: method, but that completely defeats the purpose of having a reusable cell class.

I must be missing some key concept here, but I'm at a loss. Anyone?

Thanks! randy

回答1:

You may want to take control of your layout in your UITableViewCell subclass. For example:

- (void)layoutSubviews
{
    CGRect b = [self bounds];
    b.size.width += 30; // allow extra width to slide for editing
    b.origin.x -= (self.editing) ? 0 : 30; // start 30px left unless editing
    [contentView setFrame:b];
    // then calculate (NSString sizeWithFont) and addSubView, the textField as appropriate...
    // 
    [super layoutSubviews];
}


回答2:

I think the margins are part of the cell, not the table, so that's why the contentView is always 320 wide. Maybe I don't understand the question.