Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom drawn UITableViewCell resize properly?

Tags:

iphone

For performance reasons, I draw the strings for my UITableViewCell in a custom view that overrides its drawRect method to draw strings directly in the view rectangle using NSString:drawInRect. This is similar to Apple's TableViewSuite Example 5-CustomTableViewCell.

However, when I invoke setEditing on the cell to bring up the delete button, the view ends up with a squeezed appearance after the animation completes. To demonstrate this, invoke setEditing:YES on the CustomTableViewCell example mentioned above and observe the distortion. Is there any way around this or should I just revert back to using UILabels for my text?

like image 562
drewh Avatar asked Oct 19 '08 02:10

drewh


3 Answers

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.)

like image 86
wka Avatar answered Nov 12 '22 21:11

wka


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.

like image 2
rustyshelf Avatar answered Nov 12 '22 21:11

rustyshelf


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);
}
like image 1
Sam Soffes Avatar answered Nov 12 '22 21:11

Sam Soffes