0

I have a ViewController in a storyboard consisting of two UIViews and a table at the bottom. the center of the screen contains a UIView defined in the storyboard with an outlet called middleSectionView. I want to programmatically add a subView to middleSectionView. The programmatically added subView is not appearing. Here's my code:

RoundedRect.m:
#import "RoundedRect.h"

@implementation RoundedRect

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSLog(@"RoundedRect: initWithFrame: entering");
        UIView* roundedView = [[UIView alloc] initWithFrame: frame];
        roundedView.layer.cornerRadius = 5.0;
        roundedView.layer.masksToBounds = YES;
        roundedView.layer.backgroundColor = [UIColor redColor].CGColor;

        UIView* shadowView = [[UIView alloc] initWithFrame: frame];
        shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
        shadowView.layer.shadowRadius = 5.0;
        shadowView.layer.shadowOffset = CGSizeMake(3.0, 3.0);
        shadowView.layer.opacity = 1.0;
        // [shadowView addSubview: roundedView];
    }
    return self;
}
@end


.h:
...
@property (strong, nonatomic) IBOutlet UIView *middleSectionView;

.m:
...
#import "RoundedRect.h"
...
- (void)viewDidLoad
{
    RoundedRect *roundRect= [[RoundedRect alloc] init];
    roundRect.layer.masksToBounds = YES;
    roundRect.layer.opaque = NO;
    [self.middleSectionView addSubview:roundRect];    // This is not working
    [self.middleSectionView bringSubviewToFront:roundRect];
    // [self.view addSubview:roundRect];             // This didn't work either
    // [self.view bringSubviewToFront:roundRect];    // so is commented out
    ...
}   

1 Answer 1

2

The reason why you do not see the RoundedRect is that you are calling a wrong initializer: this line

RoundedRect *roundRect= [[RoundedRect alloc] init];

does not invoke the initWithFrame: initializer that does all the work initializing your RoundedRect view. You need to change the call to

RoundedRect *roundRect= [[RoundedRect alloc] initWithFrame:CGRectMake(...)];

and put the desired coordinates of the frame in place of the ... above.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the quick reply! However, I'm still confused on this one. Adding the subview is in viewDidLoad.
@user1509295 You are welcome! If this problem is solved, consider accepting the answer by clicking the grey check mark next to it. This would let others know that you are no longer actively looking for a solution, and earn you a new badge on Stack Overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.