动态 NSLayoutConstraint

Dynamic NSLayoutConstraint

我在 iOS 故事板中有一个场景,其中包含 2 个主要元素:一个 MKMap 和一个 UITableView,请参见屏幕截图:

约束(Y 轴上的约束)是:

我有 3 个案例:

  1. 地图被隐藏,所以我只能看到 table 全屏
  2. 地图高 200 像素,table 适应屏幕
  3. 地图是全屏的,table是隐藏的

对于情况 1。我更改(以编程方式)高度约束的值并将其设置为 0。

对于情况2,我什么都不改

对于情况3,我不知道该怎么办。

我是否需要在地图上添加另一个约束,例如具有更高优先级的底部 space:0?

有很多方法可以解决这个问题,但我个人会保留对高度限制的引用,即

  • V:[mapView(==0)](案例 1),
  • V:[mapView(==200)](案例 2),或
  • V:[tableView(==0)](案例 3)。

因为最后一个约束在不同的视图上,我可能只是让我的代码删除旧约束,创建新约束,然后为约束的布局设置动画。

因此它可能看起来像:

[self.heightConstraint.firstItem removeConstraint:self.heightConstraint];

NSLayoutConstraint *constraint;
if (constraintType == 1) {
    constraint = [NSLayoutConstraint constraintWithItem:self.mapView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0.0];
} else if (constraintType == 2) {
    constraint = [NSLayoutConstraint constraintWithItem:self.mapView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:200.0];
} else if (constraintType == 3) {
    constraint = [NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0.0];
}

[constraint.firstItem addConstraint:constraint];

self.heightConstraint = constraint;

[UIView animateWithDuration:0.25 animations:^{
    [self.view layoutIfNeeded];
}];