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

    Joined:
    Mar 27, 2009
    #1
    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

    Joined:
    Mar 27, 2009
  3. waterskier2007 macrumors 68000

    waterskier2007

    Joined:
    Jun 19, 2007
    Location:
    White Lake, MI
    #3
    something like this should work

    Code:
    [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

    Joined:
    Mar 27, 2009
    #4
    Yes, thank you.
     
  5. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #5
    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

    Joined:
    Mar 27, 2009
    #6
    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