Resolved Programmatically align UIView with right side of parent using AutoLayout

Discussion in 'iOS Programming' started by moonman239, Jul 30, 2015.

  1. moonman239 macrumors 68000

    Mar 27, 2009
    I have a UIImageView that is programmatically created and added to a UITableViewCell. What I want to do is change the image view's frame so that it is as tall as the cell and its right side is aligned with the right side of the border. I have no interest in coding in a bunch of mathematical operations to accomplish this task. Will someone please help? Thanks!
  2. moonman239, Jul 30, 2015
    Last edited: Jul 30, 2015

    moonman239 thread starter macrumors 68000

    Mar 27, 2009
  3. waterskier2007 macrumors 68000


    Jun 19, 2007
    Novi, MI
    something like this should work

    [imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [tableView.contentView addSubview:imageView];
    NSDictionary *viewDict = @{@"imageView" : imageView};
    [tableViewCell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[imageView]-0-|" options:0 metrics:nil views:viewDict]];
    [tableViewCell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imageView]-0-|" options:0 metrics:nil views:viewDict]];
    [imageView addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:imageView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0]];
    Note: haven't tried it and I typed it outside of Xcode (no completion)

    Basically, you add the image view and then add 4 constraints

    the first constraint line is adding two, because you pin the image view top and bottom to the top and bottom of your tableviewcell's content view.

    The next line adds a constraint to pin the right side to the right side of your tableviewcell content view

    The next line says make the image view as wide as it is tall (but you could change this if you don't want it to be square)
  4. moonman239 thread starter macrumors 68000

    Mar 27, 2009
    Yes, thank you.
  5. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    It would usually be more convenient to add this imageView in IB and then hide/show it. You can then do the constraints in IB. Anyway, you can't see an imageView if it has no image set.
  6. moonman239 thread starter macrumors 68000

    Mar 27, 2009
    I would have gone that route, but in my case, I had other views on the cell and I'd have to deal with a little annoyance getting the image view displaying correctly. That's why I opted to create the image view programmatically.

Share This Page