1
votes

I have a custom view defined in xib file, which has an UIImageView in it.

The image is added programmatically. I don't lnow the exact image size at compile time.

Height of an imageView is constant by design, and width must be dynamic.

UIImageView should automatically resize to fit image after setting it, but it doesn't.

I've tried:

  • Setting "Intristic size = Placeholder" in UI Designer.
  • Setting different modes like "Aspect fit" or "Aspect fill"
  • Setting constraints (see screenshot)
  • Setting size in code (see code)
  • Searching at Google and Stackoverflow and trying code examples

Nothing has helped to achieve desired result.

There's my xib screenshot

There's my code:

@implementation EVACustomNavBar

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [[NSBundle mainBundle] loadNibNamed:@"EVACustomNavBar" owner:self options:nil];
        self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.frame.size.width, self.frame.size.height);
        [self addSubview:self.view];
    }
    return self;
}

-(void)setLogo:(UIImage *)logo
{
    NSLog(NSStringFromCGRect(self.logoView.bounds));
    NSLog(NSStringFromCGSize(logo.size));
    self.logoView.backgroundColor = [UIColor blackColor];
    self.logoView.image = logo;
    CGRect ivFrame = self.logoView.bounds;
    CGFloat aspectRatio = logo.size.width / logo.size.height;
    ivFrame.size.width = ivFrame.size.height * aspectRatio;
    self.logoView.bounds = ivFrame;
    NSLog(NSStringFromCGRect(self.logoView.bounds));
}

@end

I tried calling setLogo at viewDidLoad and viewDidAppear in my ViewController file.

I tried both logoView.bounds and logoView.frame. Output is:

logoView.bounds before setting: {{0, 0}, {0, 44}}
logo size: {82, 71}
logoView.bounds after setting{{0, 0}, {50.816898, 44}}

However I see this: There's my simulator screenshot

So even setting frame of UIImageView doesn't help.

1

1 Answers

2
votes

Instead of setting the bounds or frame of the image view try creating a width constraint in IB, attach it to an IBOutlet in the class and update the width constraint.