【问题标题】:How to resize view height based on it's subview avalability dynamically with Autolayout?如何使用 Autolayout 根据其子视图可用性动态调整视图高度?
【发布时间】:2015-07-04 04:00:56
【问题描述】:

我的情况是 Window 有 2 个子视图 A 和 B,而 A 视图包含另外 2 个子视图 A1 和 A2。我必须根据 A1 和 A2 是否可用来显示视图 A 的高度。 示例:如果 A1 可用,则 A2 不可用,则预期 A 的高度为 A1 高度 + 填充。并且视图 B 的高度根据视图 A 和视图 B 之间的垂直间距限制重新调整。 - 如果 A1 和 A2 都可用,则 A'height = A1 高度 + 填充 + A2 高度 + 填充。并且相同的 B 的高度根据垂直间距限制重新调整。

___________________________
| _________________________
| | A _____________________ 
| |  |_A1__________________
| |  ______________________
| | |__A2__________________
| |________________________
|
|  ________________________
| |  B
| | 
| |________________________
|
|
|__________________________


___________________________
| _________________________
| | A _____________________ 
| |  |_A1__________________
| |________________________
|
|  ________________________
| |  B
| | 
| |________________________
|
|
|__________________________

【问题讨论】:

  • 我想通了,我最终根据 A1 和 A2 视图的存在来计算 A 的高度,并更新布局。

标签: ios objective-c ios7 autolayout


【解决方案1】:

我想您已经自定义了名为LiveView 的视图,其中包含您描述的所有视图。我在下面放了一些代码,稍后再解释。

@implementation LiveView

- (id)init {
    self = [super init];
    if (!self) return nil;
    
    // Iniitlize your view hierarchy
    
    return self;
}

+ (BOOL)requiresConstraintBasedLayout
{
    return YES;
}

// this is Apple's recommended place for adding/updating constraints
- (void)updateConstraints {
    // Define or update your constraints

    // 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];
    }];
}

如您所见,您应该在- (id)init 中初始化视图层次结构。并覆盖+ (BOOL)requiresConstraintBasedLayoutmethod 并返回YES。然后覆盖应该定义或更新约束的- (void)updateConstraints 方法。当您调用方法- (void)updateConstraints 中的所有方法时,将更新您的约束和布局。

【讨论】:

    【解决方案2】:

    1.您可以使用代码提供框架

    viewA1.frame = [self frameForViewA1];

    viewA2.frame = CGRectZero;

    viewA.frame = CGRectMake(0.0f, 0.0f, DESIRED_WIDTH, viewA1.frame.size.height + DESIRED_PADDING + viewA2.frame.size.height);

    2。您可以使用容器视图

    UIView containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, DESIRED_WIDTH, viewA1.frame.size.height + DESIRED_PADDING + viewA2.frame.size.height)];

    然后为视图 A 添加 Auto Layout 约束以适应 containerView 高度。

    【讨论】:

    • 无论如何我们可以通过在界面生成器中设置约束来获得这种行为吗?前任。如果 A1,A2 是 UILabel 并且如果 A2 UILabel 没有文本,则 A2 必须缩小到 0 并根据 A 的高度重新调整。
    • 是的。通过选择第二个选项,您可以使用界面构建器(Storyboard/XIB)为容器视图设置自动布局约束。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多