【问题标题】:Weird autolayout centering issue奇怪的自动布局居中问题
【发布时间】:2020-03-29 22:08:34
【问题描述】:

这一直困扰着我。

基本上,归结为,当我使用布局锚手动定义自动布局约束并在弹出框中使用视图控制器时,中心位于错误的位置。它似乎以从弹出框弹出箭头左侧到左右边缘的边界为中心,而不是弹出框区域的中心。

这似乎适用于其他 UIViewController 表示方法,例如 UIModalPresentationFormSheet。

有什么想法可以在不特殊设置边距的情况下以布局友好的方式解决这个问题吗?

PS。如果您将布局固定到父视图的中心,则会发生完全相同的事情,它会稍微偏离。

(注:编辑因为我发布的来源不好)

-(void)loadView {

    // create root view.
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:[UIColor greenColor]];
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    self.view = view;


    UIView *parentView = [[UIView alloc] init];
    [view addSubview:parentView];

    [parentView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [parentView setBackgroundColor:[UIColor redColor]];

    [parentView.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:20.0].active = YES;
    [parentView.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-20.0].active = YES;

   [parentView.topAnchor constraintEqualToAnchor:view.topAnchor constant:10.0].active = YES;
    [parentView.bottomAnchor constraintEqualToAnchor:view.bottomAnchor constant:-10.0].active = YES;
}

【问题讨论】:

  • 您的约束不足。这是真实的代码吗?
  • 抱歉,剪切/粘贴工作失败。这些约束应该足够了,正如我所说,它适用于页面表或其他演示文稿,但不适用于弹出式演示文稿。
  • 所以我想现在的问题只是视图的边缘在哪里。您假设它们是主要区域的边缘。但也许它们包括箭头。如果箭头只是一个有助于解释它的面具。
  • 正确,它似乎居中,好像箭头是视图的一部分。我只是不确定如何干净地修复它,以某种方式可以将视图呈现为弹出框和模态叠加层,至少无需有条件地修改约束。
  • 固定到视图的margins,而不是它的edge。这就是发明边距的原因。

标签: ios objective-c autolayout


【解决方案1】:

视图的边缘不在您认为的位置;前缘是箭头的点所在的位置,而不是可见矩形的边所在的位置。

但是,边距是您所期望的。所以别针到layoutMarginsGuide,一切都会好起来的。确实,这是margin 旨在涵盖的内容之一。

在斯威夫特中:

parentView.leadingAnchor.constraint(
    equalTo: self.view.layoutMarginsGuide.leadingAnchor, constant:0).isActive = true
parentView.trailingAnchor.constraint(
    equalTo: self.view.layoutMarginsGuide.trailingAnchor, constant:0).isActive = true


(并根据需要更改那些 constant 数字。)

【讨论】:

  • 完美,谢谢。这也解释了为什么我的 NIB 大部分都可以工作,因为布局 guid 非常明显地浮动。我没有想到在没有笔尖的情况下我必须这样做。
猜你喜欢
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多