2012-08-30 49 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]; 
} 

試試這個它會工作...