This is really a n00b
question, I am learning iOS
while trying to build an app
I need to show an image, label on UITableViewCell
. The following code does that for me
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.imageView.image = [self getImageNameForRow:indexPath.row];
cell.textLabel.text = self.features[(NSUInteger) indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
return cell;
}
The problem is that image size comes bigger that I expect. so I tried to increase the height of row as
self.tableView.rowHeight = 80;
But then the image also scales up.
How can I keep my image size fixed while increasing (or changing) the size of the row?
I believe your main problem here is the image is too large. If the image were only 40x40, it would appear as half the tableViewCell's height (when it's 80). IIRC the UIImageView in that UITableViewCell stretches to the height of the cell, and images will always fill it if they're large enough.
Three things you could do:
1) Shrink the size of the image to the size you want.
2) Change the frame of the imageView manually like so:
I'm not entirely certain if you need to cache the center and re-set it after the frame change or not (the UITableViewCell might do this automatically).
3) Make a custom UITableViewCell subclass that has a fixed size UIImageView. I've detailed how to do this on my blog here.
I recommend 1 or 3.
The problem is that you are using a default table view cell style. That style comes with a built-in
textLabel
and animageView
, and the latter is a UIImageView with constraints so that it is resized to fill the height of the cell. But you have also saidWhich means that as the image view grows, the image grows with it - exactly what you are seeing.
The solution, as I explain here, is to size the image down to the actual size that you want it - and set the image view's contentMode to
center
. Something like this:Change that
36,36
to the size you actually want.This is good practice anyway. It is a terrible waste of memory to hold onto an image at a larger size than needed for actual display (the amount of wasted memory grows exponentially, because area is on the order of the square of a single dimension). So you should always size images down to their actual display size. There's lots and lots of code on Stack Overflow showing many other ways to do that.