iOS:以编程方式更改从 Interface Builder 设置的约束

标签 ios objective-c autolayout nslayoutconstraint

friend 们,美好的一天!

我未能尝试通过代码为 IB 中设置的 View 设置动画。应用程序崩溃,原因如下:

The view hierarchy is not prepared for the constraint...

我在这里看到了一些类似的问题,原因总是以编程方式创建的 View 尚未添加到 super View 中。但是我在 IB 中创建了所有 View !

控制台还说:

View not found in container hierarchy: (here goes it's superview)

这对我来说没有任何意义,因为实际上它是适当 super View 的 subview ,而且 xcode 知道它 - 它会立即打印 View 层次结构并且它适合。

可能是什么原因? 谢谢!

编辑:我使用的代码:

    - (void)setEditingConstraintsForView:(UIView *)view
{
    // Pin given view to top, fix it height
    NSDictionary *givenView = @{@"view":view};
    view.translatesAutoresizingMaskIntoConstraints = NO;

    NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:givenView];
    NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view(height)]" options:0 metrics:@{@"height":@(viewHeight)} views:givenView];

    [self.animatedVIew addSubview:view];

    for (NSArray *constraints in @[horizontalConstraints, verticalConstraints]) {
        [view addConstraints:constraints];
    }
}

另外,我在安装新的之前删除了我在 IB 中设置的所有约束:

    - (NSDictionary *)constraintsFromIB
{
    if (!_constraintsFromIB) {
        _constraintsFromIB = @{@"view1":self.view1.referencingConstraintsInSuperviews,
                               @"view2":self.view2.referencingConstraintsInSuperviews,
                               @"view3":self.view3.referencingConstraintsInSuperviews };
    }

    return _constraintsFromIB;
}

然后:

- (void)updateViewConstraints
{
    [super updateViewConstraints];

    // clear all constraints
    for (NSString *viewName in self.constraintsFromIB.allKeys) {
        for (NSLayoutConstraint *constraint in self.constraintsFromIB[viewName]) {
            [constraint remove];
           }

}

更新 2:我使用调用更改的方法:当用户触摸 View 时,调用此 View :

- (void)animateConstraintsForState:(LDYEditingLabel)state
{
    self.editingLabel = state;        
    [UIView animateWithDuration:0.3 animations:^{
        [self updateViewConstraints];
        [self.view layoutIfNeeded];
    }];
}

稍后在 updateViewConstraints: 中有一段代码触发了我的方法 setEditingConstraintsForView:(UIView *)view

最佳答案

如果您使用 IB 创建约束,您可以添加约束作为导出。

然后更新约束并调用 [self updateViewConstraints];在动画 block 中

enter image description here

关于iOS:以编程方式更改从 Interface Builder 设置的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27976198/

相关文章:

javascript - 需要相机叠加(半透明)图片HowTo

ios - Ionic 4 在 iOS 设备上运行应用程序时出现电容器错误

ios - 将 ReactiveCocoa 中的信号组合成一个在所有变化时触发的新信号

ios - 在 iOS 中将项目放置在屏幕中央

ios - 在导航栏中使用提示时自动布局警告

ios - UITextView 总是滚动到内容的底部?

ios - 希望快速将用户输入发送到网络服务器并加载结果

iOS:当 SignaturePadView 在 UIScrollView 中时,如何防止滚动?

iOS:如果从 Storyboard拖入,如何为点击手势识别器编写处理程序?

iphone - iOS 6 UITextView 无法删除相等约束