【问题标题】:UIView addSubview auto layout not workingUIView addSubview 自动布局不起作用
【发布时间】:2014-10-31 03:13:46
【问题描述】:

我以编程方式创建了一个 UIView 并将 NSLayoutConstraint 添加到它并且它可以工作,然后将它添加为视图控制器视图的子视图。现在我需要从超级视图中删除这个视图,稍后再添加它。但是如果我使用self.view addSubview 再次添加它,布局将不再起作用。如何让布局再次生效?

【问题讨论】:

  • 您需要重新添加约束。删除子视图时,该视图的所有约束都将丢失。

标签: ios uiview autolayout


【解决方案1】:

问题是子视图不继承原始视图的大小/框架,因此添加视图就好像它卡在 600x600 的任意 + 任意大小中一样。我的解决方案是,设置原始视图的框架,然后让 iOS 完成剩下的工作。

[self.myOtherView setFrame:self.view.frame];   //Replace frame size with already resized view
[self.myOtherView setNeedsLayout];  //Tell iOS to autolayout the new sub view
[self.addSubView:self.myOtherView];  //Add it

【讨论】:

    【解决方案2】:

    在自动布局中添加和删除视图时需要注意一些问题。

    UIView.h 类中提供了两种方法

    // Allows you to perform layout before the drawing cycle happens. 
    //   -layoutIfNeeded forces layout early
    - (void)setNeedsLayout;
    - (void)layoutIfNeeded;
    

    根据您的要求使用这些方法。所以我建议当你从视图中删除子视图时,如果需要,更新上级视图的约束。然后调用下面的方法来反映布局的变化。

    [self.view layoutIfNeeded];
    

    上述方法的大多数情况将解决所有与布局相关的问题。但是,如果存在复杂的结构,有时我的意思是视图的运行时改变行为。

    然后在您的UIViewController 中覆盖下面的方法,在此方法中执行所有与框架相关的更改。

    - (void)viewDidLayoutSubviews
    

    【讨论】:

      【解决方案3】:

      创建约束时将其分配给变量

      @property (nonatomic, strong)NSLayoutConstraint *viewConstraintTop;
      self.viewConstraintTop = [Your Constraint];
      

      当你想从超级视图中移除它时,移除约束

      [self.viewConstraintTop autoRemove];
      

      删除您的视图并再次添加约束分配为

      self.viewConstraintTop = [Your Constraint];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多