2012-08-30 47 views
2

我想以编程方式将myView添加到父视图。但它不显示在屏幕上。代码有什么问题?为什么addSubview不显示?

@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]; 
} 
+0

尝试'@prop erty(非原子,强大)UIView * myView;' – janusbalatbat

+0

谢谢,这是有效的。但我想知道为什么?将属性设置为strong使得myView被控制器(self)和self.view保留两次。那是对的吗?为什么弱不行? – Philip007

+0

不,它是唯一的子视图。看来财产确实是相关的,因为改变弱到强解决问题。 – Philip007

回答

7

更换

@property (nonatomic,weak) UIView *myView; 

@property (strong, nonatomic) UIView *myView; 

,它应该工作:)

2
@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]; 
} 

试试这个它会工作...