Reputation: 827
I'm trying to add an Image to my view. I tried the following code:
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tag40pixelsborder.png"]];
imgView.frame = CGRectMake(200, 200, 30, 30);
// imgView.bounds = CGRectMake(300, 300, 32, 32);
[imgView setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgView];
NSLog(@"frame x %f", imgView.frame.origin.x);
NSLog(@"frame y %f", imgView.frame.origin.y);
But the picture doesn't appear on screen, and NSLog return 30.00 for "x" and 0.00 for "y" If I uncomment the bounds line and I remove the frame line, I get 80.00 for "x" and 80.00 for "y".
I am using autolayout, but the exact same code works on another view! What's wrong?
Upvotes: 0
Views: 1827
Reputation: 2830
If you wish to use auto layout to do this then you should do something along these lines.
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tag40pixelsborder.png"]];
imgView.translatesAutoresizingMaskIntoConstraints = NO;
[imgView setContentMode:UIViewContentModeScaleAspectFit];
[imgView sizeToFit];
[self.view addSubview:imgView];
Then you will want to set the auto layout constraints what i see you have is x = 200 y = 200
NSArray *constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-(200)-[imgView]"
options:0
metrics:nil
views:@{ @"imgView" : imgView }];
[self.view addConstraints:constraints];
constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"|-(200)-[imgView]"
options:0
metrics:nil
views:@{ @"imgView" : imgView }];
[self.view addConstraints:constraints];
The above will make the image view 200 from the top and 200 from the left of the parent view i.e. self.view in this case.
If you wanted to add the heights you could remove the [imgView sizeToFit] and just add heights to the width and height constraints i.e. |-(200)-[imgView(width)] and same for the height in the one marked with the V:.
Upvotes: 1
Reputation: 13860
If you're using autolayout
like you said you should avoid to add subviews from code! If you want to do this you should programmatically add constrains
also. Your code is fine but autolayout are messing with it. If you want dirty solution you should add this ImageView after everything is loaded (in viewDidAppear:
method for example).
Upvotes: 1