iOS:如何获得布局使用Masonry的视图边界

时间:2016-06-06 08:49:43

标签: ios masonry

我有一个问题 我使用砌体布局statusBar。现在我想在statusBar中添加一个CAGradientLayer。所以我需要获得statusBar.bounds。但界限是零。并且砌体不能为图层添加约束。非常感谢你! 这是我的代码:

self.statusBar = [[UIView alloc] init];
    [self addSubview:self.statusBar];
    [_statusBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self);
        make.height.equalTo(@(20));
        make.top.left.equalTo(@(0));
    }];
    [self setStatusBarColorWithStartColor:[UIColor blackColor] endColor:[UIColor grayColor]];

- (void)setStatusBarColorWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor
{
    // init CAGradientLayer
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
NSLog(@"%@", NSStringFromCGRect(self.statusBar.frame));
gradientLayer.frame = self.statusBar.bounds; // bound is zero
[self.statusBar.layer addSublayer:gradientLayer];

// set gradient colors
gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];

// set star and end point
gradientLayer.startPoint = CGPointMake(0.0f, 0.5f);
gradientLayer.endPoint = CGPointMake(1.0f, 0.5f);

// optional set locations

}

2 个答案:

答案 0 :(得分:1)

我认为你需要这样的东西:

 [self.statusBar mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(@(0));
    make.top.equalTo(@(0));
    make.right.equalTo(@(0));
    make.height.equalTo(@(20));
  }];

答案 1 :(得分:1)

您可以通过覆盖视图的方法 layoutSubviews 获取正确的框架和边界,或者查看控制器的 viewDidLayoutSubviews 。请注意,这两个选择器将被多次调用, viewDidLayoutSubviews 需要调用 [super viewDidLayoutSubviews]