Change size of image view programmatically

I've developed an app for iphone with an image view whose size is changed by the program.

This only works without auto layout.

When I change to universal device with autolayout the size of image view can not be changed programmatically.


Can anyone help?


ViewController.h:


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIImageView *firstImage;

@end


ViewController.m:


@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];


_firstImage.frame = CGRectMake(10,100,100, 12);


@end

Possibly, the image size changes and then auto layout set the size back.

What are the constraints associated with this view ? (look into size inspector for the imageView).


Once you have found what are the constraints that cause the problem, one way to solve it is to disable the constraints associated with the image:

- create an IBOutlet for each constraint

- then, in viewDidLoad, set active to false for the constraint


Another possible cause is that you have to use NSImage(CGImage, size) ; and thus convert NSImage to CGImage first


Have a look at stackoverflow.com/questions/24595908/swift-nsimage-to-cgimage

Hi Caude31, thanks a lot for your response.


I've tried with constraints, for examble a left margin contraint and a top margin contraint and I've tried without constraint.

I've tried with an IBOutlet for each contraint and deactivate them in viewDidLoad.

Always with the same result. Image size doesn't change.


At stackoverflwo I found the solution:


self.firstImage.translatesAutoresizingMaskIntoConstraints = YES;


http://stackoverflow.com/questions/11368440/can-i-disable-autolayout-for-a-specific-subview-at-runtime


Don't know why (I'm a beginner), but it works :-)

Here is what the doc says :


translatesAutoresizingMaskIntoConstraints
Property

When this property is set to

YES
, the view’s superview looks at the view’s autoresizing mask, produces constraints that implement it, and adds those constraints to itself (the superview). If your view has flexible constraints that require dynamic adjustment, set this property to
NO
and apply the constraints yourself.


What is surprising me is that it's set to NO by default.

... perhaps to make life harder 😁

Change size of image view programmatically
 
 
Q