Philip007
Philip007

Reputation: 3230

Why addSubview doesn't show?

I wanted to programmatically add myView to parent view. But it doesn't show up on screen. What's wrong with the code?

@interface ViewController ()
@property (nonatomic,weak) UIView *myView;
@end

@implementation ViewController
@synthesize myView = _myView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect viewRect = CGRectMake(10, 10, 100, 100);
    self.myView = [[UIView alloc] initWithFrame:viewRect];
    self.myView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.myView];
}

Upvotes: 3

Views: 10834

Answers (2)

user1986441
user1986441

Reputation:

@interface ViewController ()

@end

@implementation ViewController

UIView *myView;

-(void)viewDidLoad
{
    [super viewDidLoad];

    CGRect viewRect = CGRectMake(10, 10, 100, 100);

    myView = [[UIView alloc] initWithFrame:viewRect];

    myView.backgroundColor = [UIColor redColor];

    [self.view addSubview:myView];
}

try this it will work…

Upvotes: 2

user1629713
user1629713

Reputation: 146

Replace

@property (nonatomic,weak) UIView *myView;

with

@property (strong, nonatomic) UIView *myView;

and it should work :)

Upvotes: 8

Related Questions