0

I want to Displays the content (including image, title and description) in a table. I am trying to set autolayout for same. but my image is getting shrink according to cell height. But I want to show image as original (all images are of diff. height width)

 UIImageView *customImageView;
        UILabel *customLabel;


        customImageView = [[UIImageView alloc] init];
        customImageView.translatesAutoresizingMaskIntoConstraints = NO;
        customImageView.tag = indexPath.row + 100;
        customImageView.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:customImageView];

        customLabel = [[UILabel alloc] init];
        customLabel.translatesAutoresizingMaskIntoConstraints = NO;
        customLabel.tag =  indexPath.row + 500;
        customLabel.numberOfLines = 0;
        customLabel.lineBreakMode = NSLineBreakByWordWrapping;

        [cell.contentView addSubview:customLabel];

        NSDictionary *views = NSDictionaryOfVariableBindings(customImageView, customLabel);
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[customImageView(160)]-[customLabel]|" options:0 metrics:nil views:views]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[customImageView]-3-|"                 options:0 metrics:nil views:views]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[customLabel]-3-|"                     options:0 metrics:nil views:views]];

1.HOw can i show image as it is 2.how can I add another label for description below title label using constraints? Can you please suggest some solution or guide me on this?

New iOS Dev
  • 1,937
  • 7
  • 33
  • 67

1 Answers1

0

All that you need is UITableViewAutomaticDimension. ImageView's has implicit size. ImageViews take size based on the image set to them. When your cell contains the components with implicit sizes you can make use of UITableViewAutomaticDimension to tell the tableView to size the cell based on the size of imageView.

make sure you set the imageView's content mode set to center

Code :

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 140

Don't write height for row at indexPath :)

O/P:

enter image description here

Look at cell sizes. Changing their size automatically based on image.

EDIT :

Forgot to mention the only auto layout constraint added to imageView and cell are trailing, leading, top and bottom constraints with constant 0 to cell.

enter image description here

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78