Ios 旋转设备和自动布局时强制更改子视图背景色
自定义视图和自动布局有问题。为了简单起见,我将使用两个UILabel,第一个应该在设备旋转时更改其背景颜色。问题是它不能做到!有什么提示吗? 谢谢 尼古拉Ios 旋转设备和自动布局时强制更改子视图背景色,ios,uiview,autolayout,screen-rotation,Ios,Uiview,Autolayout,Screen Rotation,自定义视图和自动布局有问题。为了简单起见,我将使用两个UILabel,第一个应该在设备旋转时更改其背景颜色。问题是它不能做到!有什么提示吗? 谢谢 尼古拉 如果将与[self.label1 setBackgroundColor:相关的代码移动到委托方法didRotateFromInterfaceOrientation:,它应该工作得更好。此外,在自定义getter中,每次访问该方法时都会分配一个新标签。在大多数情况下,最好在开始时检查ivar是否为零,然后返回ivar,而不是分配新标签 - (i
如果将与
[self.label1 setBackgroundColor:
相关的代码移动到委托方法didRotateFromInterfaceOrientation:
,它应该工作得更好。此外,在自定义getter中,每次访问该方法时都会分配一个新标签。在大多数情况下,最好在开始时检查ivar是否为零,然后返回ivar,而不是分配新标签
- (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];
}