【问题标题】:iOS8 how to fit a square view into rectangular parent using storyboard with autolayout and size classes?iOS8如何使用带有自动布局和大小类的故事板将方形视图放入矩形父级?
【发布时间】:2015-01-22 11:06:56
【问题描述】:

我正在使用带有自动布局和大小类的UIStoryboard 来处理在横向模式下旋转 iPhone。我正在动态地将视图大小调整为两个容器,每个容器都是矩形(如 300x260),并试图将方形视图放入该容器中。我希望视图能够选择矩形的较小尺寸并适当地调整其大小:

例如:

  • 在 300x260 容器中,我希望我的视图是 260x260 正方形
  • 在 240x300 容器中,我希望我的视图是 240x240 正方形

夸张的例子:

我是否可以使用一些巧妙的自动布局技巧来确保视图将使用情节提要选择其父级的较小尺寸(大小或宽度)?我尝试了 1:1 纵横比约束,但视图仍在裁剪(选择不正确的尺寸)

【问题讨论】:

    标签: iphone ios8 autolayout uistoryboard size-classes


    【解决方案1】:

    除了比率约束之外,您还需要添加两个约束。一种指定内视图的高度小于外视图的高度,一种指定内视图的宽度小于外视图的宽度。

    您可能可以在 Interface Builder 中执行此操作,但在代码中它会是这样的:

    UIView *outerView = ...;
    UIView *innerView = ...;
    [outerView addConstraints:@[
         [NSLayoutConstraint constraintWithItem:innerView
                                      attribute:NSLayoutAttributeWidth
                                      relatedBy:NSLayoutRelationLessThanOrEqual
                                         toItem:outerView
                                      attribute:NSLayoutAttributeWidth
                                     multiplier:1.0
                                       constant:0.0],
         [NSLayoutConstraint constraintWithItem:innerView
                                      attribute:NSLayoutAttributeHeight
                                      relatedBy:NSLayoutRelationLessThanOrEqual
                                         toItem:outerView
                                      attribute:NSLayoutAttributeHeight
                                     multiplier:1.0
                                       constant:0.0],
    ]];
    

    您可能还需要添加低优先级约束以使内部视图的大小大于零。

    【讨论】:

    • 谢谢,这行得通,我需要为父级添加
    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2013-11-07
    • 2015-11-09
    相关资源
    最近更新 更多