2013-08-21 3 views
0

사용자 정의보기 및 자동 레이아웃에 문제가 있습니다. 일을 단순하게하기 위해 두 개의 UILabels를 사용합니다. 첫 번째는 장치가 회전 할 때 배경색을 변경해야합니다. 문제는 그것이 그것을하지 않는다는 것입니다! 어떤 힌트? 감사합니다. 당신이 대리자 메서드 didRotateFromInterfaceOrientation:[self.label1 setBackgroundColor:] 관련된 코드를 이동하는 경우 니콜라장치 및 자동 레이아웃을 회전 할 때 하위보기 배경색이 변경됩니다.

- (id)init 
{ 
    self = [super init]; 
    if (self) { 

     //Add the subviews to the mainView 
     [self.view addSubview:self.label1]; 
     [self.view addSubview:self.label2]; 

     //Autolayout 

     //Create the views dictionary 
     NSDictionary *viewsDictionary = @{@"header":self.label1, 
              @"table": self.label2}; 

     //Create the constraints using the visual language format 

     [self.view addConstraints:[NSLayoutConstraint 
      constraintsWithVisualFormat: @"H:|[header]|" 
           options:0 
           metrics:nil 
           views:viewsDictionary]]; 

     [self.view addConstraints:[NSLayoutConstraint 
      constraintsWithVisualFormat: @"H:|[table]|" 
           options:0 
           metrics:nil 
           views:viewsDictionary]]; 

     [self.view addConstraints:[NSLayoutConstraint 
      constraintsWithVisualFormat:@"V:|[header(==50)][table]|" 
           options:0 
           metrics:nil 
           views:viewsDictionary]]; 

    } 
    return self; 
} 


-(UIView*) label1 
{ 
    _label1 = [UILabel alloc] init]; 

    if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)){ 
     _label1.backgroundColor = [UIColor redColor]; 
    }else{ 
     _label1.backgroundColor = [UIColor greenColor]; 
    } 

    _label1.translatesAutoresizingMaskIntoConstraints=NO; 
    return _label1; 
} 

-(UIView*) label2 
{ 
    _label2 = [UILabel alloc] init]; 
    _label2.backgroundColor = [UIColor yellowColor]; 
    _label2.translatesAutoresizingMaskIntoConstraints=NO; 
    _return label2; 
} 

-(BOOL) shouldAutorotate 
{ 
    return YES; 
} 

-(NSUInteger) supportedInterfaceOrientations 
{ 
    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){ 
     //I am on a pad 
     return UIInterfaceOrientationMaskAll; 
    } else { 
     //I am on a Phone 
     return UIInterfaceOrientationMaskAllButUpsideDown; 
    } 
} 

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 
{ 
    //I expect the label1 to change its background color 
    [self.view setNeedDisplay]; 
} 

답변

0

, 더 나은 작동합니다. 또한 사용자 정의 getter에서 메소드에 액세스 할 때마다 새 레이블을 할당합니다. 대부분의 상황에서 ivar이 처음에는 nil이 아니고 ivar을 반환하는지 확인하는 것이 좋습니다. 대신 새 레이블을 할당하는 것이 좋습니다.