Le Mot Juiced Le Mot Juiced - 1 year ago 66
iOS Question

Adding a UIImageView as a subview of UILabel, image not appearing

So, when I do this with a regular old view:

UIView *topBlock = [[UIView alloc] initWithFrame:CGRectMake(0,-frameSize.height, frameSize.width, frameSize.height/2)];
[viewController.view addSubview:topBlock];
topBlock.autoresizesSubviews = NO;
topBlock.clipsToBounds = YES;
UIImage *topImage = [UIImage imageNamed:@"BloktLayout"];
UIImageView *topImageView = [[UIImageView alloc] initWithImage:topImage];
topImageView.frame = viewController.view.frame;
[topBlock addSubview:topImageView];

I get the nice old image where I want it, in the top view. But the middle view is a UILabel, and when I try the same thing:

UILabel *midBar = [[UILabel alloc] initWithFrame:CGRectMake(midBarOrigin.x, midBarOrigin.y, midBarWidth, midBarHeight)];
midBar.text = @"Blokt";
midBar.textColor = [UIColor blackColor];
midBar.textAlignment = NSTextAlignmentRight;
midBar.font = [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:80.0f];
[viewController.view addSubview:midBar];
midBar.autoresizesSubviews = NO;
midBar.clipsToBounds = YES;
UIImage *midImage = [UIImage imageNamed:@"BloktLayout"];
UIImageView *midImageView = [[UIImageView alloc] initWithImage:midImage];
midImageView.frame = viewController.view.frame;
[midBar addSubview:midImageView];

I don't see any image at all in the UILabel. Any help?

Answer Source

Seems like the issue is related to your frames.

Tough to say without additional info. Can you post viewController.view.frame, frameSize, and midBarOrigin / midBarWidth / midBarHeight?

In the second codeblock, midBar.clipsToBounds == YES, but it looks like the midImageView.frame is likely very different / outside of midBar.frame in which case it wouldn't be visible.

Edit Some screenshots would help but aren't necessary

Edit 2 Note that subviews' origin points are always relative to the coordinate system of their superview, never relative to the coordinate system of any other view in the view heierarchy. This is likely the heart of the issue here. If you do want to convert CGPoints or CGRects from one coordinate system to another there are methods on UIView such as convertRect: and convertPoint: etc.