Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing UITableViewCell content width automatically

I have some code that creates a table cell with a slider. It's pretty straightforward and it sizes well on the iPhone. I've anonymized it a bit here:

UITableViewCell* cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Foo"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
CGRect contentViewFrame = cell.contentView.frame;
CGRect sliderFrame = CGRectMake(10, 0, 280, contentViewFrame.size.height);
UISlider* slider = [[UISlider alloc] initWithFrame:sliderFrame];
UIImage* minimumImage = [UIImage imageNamed:@"min.png"];
UIImage* maximumImage = [UIImage imageNamed:@"max.png"];
slider.minimumValueImage = minimumImage;
slider.maximumValueImage = maximumImage;
slider.value = 0.5f;
[slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[cell.contentView addSubview:slider];
[slider release];

Of course, this is incorrectly sized for the iPad. So my first thought was to set the autoresizingMask property to UIViewAutoresizingFlexibleWidth. Problem solved, right? Nope. Now on the iPhone, the width of the slider-plus-images content is less than 280 and so it doesn't go right to the end -- it ends up about 20 pixels short.

On the iPad, the same thing -- the width of the UISlider automatically resizes to about 20 pixels short of the end of the cell.

Perhaps the auto resize flag is paying attention to the non-existent accessoryView of the cell? I tried setting it to nil explicitly, but I think it's nil by default, so nothing changed.

I'd like this cell's content to resize automatically to be the "full" width of the cell, regardless of device and orientation. Is there an easy way to do this?

like image 690
Shaggy Frog Avatar asked Jul 28 '10 22:07

Shaggy Frog


2 Answers

It works exactly how you described. I am inclined to think it's iOS bug. On iPAD when you create new UITableViewCell its width set for 320. hardcoded(!) both view and contentView. It does not resize properly if set to UIViewAutoresizingFlexibleWidth. I had it set to view.frame.size.width/2 with funny results: on iPhone it's 160, on iPad it's 608!!!

I ended up manually resizing my cells and their content.

like image 66
bioffe Avatar answered Oct 12 '22 23:10

bioffe


Bit late but i found the solution of the same question today, but you need to create a custom UITableViewCell. Then you can overwrite the function

- (void) layoutSubviews
{
    [dateLabel setFrame:CGRectMake(10.f, 16.f, 80.f, 12.f)];
    [textLabel setFrame:CGRectMake(106.f, 16.f, contentView.frame.size.width-105.f + 1.f, 12.f)];
}

In that function the self.frame.size.width is the actual one.
And it works with rotation of the device, too.

like image 29
Seega Avatar answered Oct 12 '22 22:10

Seega