Masonry中center的误区

我们平常使用masonry中相对居中对齐很简单,直接就是.center.equalTo(view),就可以了。但是如果我们只获得一个坐标点,然后根据这个坐标点进行对齐,就会出现各种问题

- (UILabel *)markLabel
{
    if (!_markLabel) {
        _markLabel = [[UILabel alloc] init];
        _markLabel.backgroundColor = [UIColor greenColor];
        _markLabel.text = @"测试";
    }
    return _markLabel;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.markLabel];
    [self.markLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(0);
        make.size.mas_equalTo(CGSizeMake(60, 20));
    }];
}
// 这个只是模拟的,当我们只获取到一个点的时候怎么办
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point = self.pointView.center;
    
    [self.markLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@(point.x));
        make.bottom.equalTo(@(point.y));
    }];
}

上面那样写,会出问题,因为markLabel完全不知道会出现在哪里。
但是我们可以改进它,这里提供一个思路
比如,在point中心点创建一个view,然后我们再相对于这个view进行布局就可以了

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point = self.pointView.center;
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(point.x -  0.5, point.y - 0.5, 1, 1)];
    v.backgroundColor = [UIColor blackColor];
    [self.view addSubview:v];
    [self.markLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(v);
        make.bottom.equalTo(v.mas_top);
    }];
}

这样就搞定了。

你可能感兴趣的:(Masonry中center的误区)