0

我对自定义视图和自动布局有疑问。为简单起见,我将使用两个 UILabel,第一个应该在设备旋转时更改其背景颜色。问题是它不这样做!有什么提示吗?谢谢!尼古拉

- (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];
}
4

1 回答 1

0

如果您移动与[self.label1 setBackgroundColor:]委托方法相关的代码didRotateFromInterfaceOrientation:,它应该会更好。此外,在您的自定义 getter 中,您每次访问该方法时都会分配一个新标签。在大多数情况下,最好在开始时检查 ivar 是否不为零,然后返回 ivar,而不是分配新标签。

于 2013-08-21T11:01:10.463 回答