简体   繁体   中英

Create UIImageView programmatically

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?

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).

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 ie 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 ie |-(200)-[imgView(width)] and same for the height in the one marked with the V:.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM