How to make a custom drawn UITableViewCell resize properly?

心不动则不痛 提交于 2019-12-03 08:20:09

I had a similar problem with a UIView inside a UITableViewCell. I solved it by changing the UIView's contentMode to UIViewContentModeLeft. (I wrote it up here, with screenshots.)

I had this problem too, and in my case I fixed it by handling the 2 states in my drawRect method, one while editting, the other while not. In other words I accounted for the size of the delete button, and got my UI to repaint the cell differently. I'm not sure if it's the most efficient way to go, but here is the code that I used to force a repaint:

-(void)_refreshTableAndCells{
    //refresh the table
    [myCustomTableView reloadData];
    //refresh all the visible cells
    for (UITableViewCell *cell in myCustomTableView.visibleCells){
        LocationCellView *locationCell = [cell.contentView.subviews objectAtIndex:0];
        [locationCell setNeedsDisplay];
    }

}

I'm an Objective-C n00b though, so I'd be more than happy for someone to suggest a better way than this.

I usually just modify the x and width values (or whatever else) of whatever I want to be different when editing or not. UITableView automatically calls layoutSubviews when you begin editing, so you don't have to loop through your cells and do it yourself.

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat editingPadding = 5.0;
    self.textLabel = CGRectMake((self.editing ? self.textLabel.frame.origin.x + editingPadding : self.textLabel.frame.origin.x), self.textLabel.origin.y, (self.editing ? self.textLabel.frame.size.width - editingPadding : self.textLabel.frame.size.width), self.textLabel.frame.size.height);
}
lukhnos

Try setting the contentMode of your own custom view (which resides inside the cell's contentView) to UIViewContentModeLeft. The "squeezing" is due to the fact that the default contentMode is UIViewContentModeScaleToFill.

标签