Masonry学习之设置新的约束

来源:互联网 发布:淘宝开店可以注销吗 编辑:程序博客网 时间:2024/06/07 00:54

例:主视图中有一个Button,位于主视图左上角,距离主视图的top、left的偏移为10,它的大小是100x100;当点击它的时候,它的大小没变,位置移动到右下角,其right、bottom距离主视图的right、bottom的偏移也均为10。

这个例子与上一节的更新约束有什么不同呢?同样是约束发生了变化,上一节,只是约束的值发生的变化,约束的属性没发生变化,都是宽和高的改变。而这一节,当button位于左上角时,约束使用的属性是top、left和宽高,当移动到右下角时,新的约束将使用的属性是right、left和宽高。这意味着我们必须添加新的约束以取代原有的约束。

+ (BOOL)requiresConstraintBasedLayout{    return YES;}
// this is Apple's recommended place for adding/updating constraints- (void)updateConstraints {    [self.movingButton remakeConstraints:^(MASConstraintMaker *make) {        make.width.equalTo(@(100));        make.height.equalTo(@(100));        if (self.topLeft) {            make.left.equalTo(self.left).with.offset(10);            make.top.equalTo(self.top).with.offset(10);        }        else {            make.bottom.equalTo(self.bottom).with.offset(-10);            make.right.equalTo(self.right).with.offset(-10);        }    }];    //according to apple super should be called at end of method    [super updateConstraints];}
- (void)toggleButtonPosition {    self.topLeft = !self.topLeft;    // tell constraints they need updating    [self setNeedsUpdateConstraints];    // update constraints now so we can animate the change    [self updateConstraintsIfNeeded];    [UIView animateWithDuration:0.4 animations:^{        [self layoutIfNeeded];    }];}

代码结构大体与上节类似,关键在于这里使用的不再是updateConstraints,而是remakeConstraints。你可以跟进去查看其代码,将会发现,在添加新的约束之前,旧的约束会被删除。

原创粉丝点击