Darren
Darren

Reputation: 10129

Custom UITableViewCell with an optional image

I have a custom UITableView cell that has a UIImageView sized to the width of the cell at the top, and a UILabel underneath it.

A UITableViewCell has an imageView property. If the image view's image is set, then it pushes the cell textLabel to the right, to accomodate the image. I would like to do something similar with my table view cell (except that my label would be pushed down).

How could I accomplish this?

Upvotes: 1

Views: 732

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

A simple way to do it is to subclass UITableViewCell and override layoutSubviews method.

Here a simple example.

@interface CustomCell : UITableViewCell

@end

@implementation CustomCell

- (void)layoutSubviews
{
   [super layoutSubviews];

   // grab bound for contentView
   CGRect contentViewBound = self.contentView.bounds;

   if(self.imageView.image) {
      // do stuff here, for example put the image right...
      CGRect imageViewFrame = self.imageView.frame;
      // change x position
      imageViewFrame.postion.x = contentViewBound.size.width - imageViewFrame.size.width;
      // assign the new frame
      self.imageView.frame = imageViewFrame;
   }

   else {
      // do stuff here
   }
}

In particular inside this method you can position the components for your cell depending on image.

Hope it helps.

Upvotes: 2

Related Questions