0

I have 3 UIImageView and each contains an image. I have an if statement that when triggered should change the width of the image.

I have tried:

relaxedV.frame = CGRectMake(0, 53, 320, 479);
relaxedV.frame = CGSizeMake(0, 53, 320, 479);
relaxedV.image = CGRectMake(0, 53, 320, 479);
relaxedV.image = CGSizeMake(0, 53, 320, 479);

and a few others but nothing works so far. How can I just change the width? Is there a better way to do this than using a UIImageView? The images are just solid colors so I could just have them drawn with code if someone could instruct me that too

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Max
  • 3
  • 2

1 Answers1

1

Here is the several cases.

  1. You may using AutoLayout. In that case setting frames manually is discouraged, you should change the constraints instead. Read here at the SO for further information

  2. You may use AutoresizingMask. If it is set to adjust width to superview or something like that, it is also discouraged to break that rules. Instead reconsider your autoresizing mask settings

  3. You do it manually. In that case, you may use the following code to change only the width:

Code:

CGRect relaxedVframe = relaxedV.frame;
relaxedVframe.size.width = newWidth;
relaxedV.frame = relaxedVframe;

You also mention that your images are only solid color, then I would like to recommend you the following approach:

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

You may use that code to put solid-colored image to any sized UIImageView

Community
  • 1
  • 1
Azat
  • 6,745
  • 5
  • 31
  • 48
  • You can also do: `relaxedV.frame = CGRectMake(CGRectGetMinX(oldFrame), CGRectGetMinY(oldFrame), newWidth, CGRectGetHeight(oldFrame));` – NSWill May 11 '15 at 20:22
  • @Azat You should probably return a resizableImage. – Tobias May 11 '15 at 20:32
  • @Tobias it works perfectly even without that, because it is only a solid color and you cannot distinguish its pixellation. Anyway, thank you for the comment! – Azat May 11 '15 at 20:34
  • Yeah. I just like returning a resizableImage because it's ready for use on button backgrounds and other stretchable controls. – Tobias May 11 '15 at 20:36
  • I tried that and the image width still does not change. Can you think of any reason why? – Max May 12 '15 at 16:37
  • Don't you use neither `AutoLayout` nor `AutoresizingMask`? – Azat May 12 '15 at 21:07