【问题标题】:iOS how to center two view via PureLayoutiOS 如何通过 PureLayout 使两个视图居中
【发布时间】:2015-05-27 12:04:44
【问题描述】:

我想将我的 UIImageView 和 UILabel 居中,如下图所示。 我使用了一个容器来包含UIImageView和UILabel,但是容器不适合UIImageView和UILabel的宽度,所以我需要设置容器的宽度。有什么方法可以解决问题而不设置宽度或计算视图的宽度?图片如下:

【问题讨论】:

    标签: ios width containers pure-layout


    【解决方案1】:

    有四种视图在起作用:

    1. 外部或主视图
    2. 容器视图(包含图像和标签)
    3. 图像视图
    4. 标签视图

    视图位于以下层次结构中:

    1. 外观
      1. 容器视图
        1. 图像视图
        2. 标签视图

    我假设外部视图的宽度和高度来自其他约束。

    我从您提供的图像中看到的图像比标签高,请记住,遵循约束可以实现您想要的:

    1. 将容器视图的 X 轴与外部视图对齐
    2. 将容器视图的 Y 轴与外部视图对齐
    3. 将图像视图的顶部、左侧和底部边缘固定到容器视图
    4. 将标签的右边缘固定到容器视图
    5. 将标签的 Y 轴与容器视图对齐。
    6. 设置图像和标签视图之间的水平距离。

    【讨论】:

    • 这样的评论值得在stackoverflow上回答。坚持下去。
    • 它有效!在我的情况下,我对外部视图尊重其父级设置了宽度约束,我这样做是因为标签文本是动态的并且它可能会溢出
    • Align Y axis of label to container view,不应该是X axis吗?
    【解决方案2】:
    [self.button autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
    [self.button autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
    [self.button autoSetDimension:ALDimensionHeight toSize:46];
    [self.button autoAlignAxis:ALAxisVertical toSameAxisOfView:self.contentView];
    
    [self.containerView autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
    [self.containerView autoAlignAxisToSuperviewAxis:ALAxisVertical];
    
    [self.iconImageView autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.containerView];
    [self.iconImageView autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
    
    [self.label autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.containerView];
    [self.label autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
    
    [self.label autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.iconImageView withOffset:10];
    

    感谢@abdullah。他清除了我的思绪。我忘了“将标签的右边缘固定到容器视图”,所以 containerView 的 width 变成了 0。

    【讨论】:

      【解决方案3】:

      这是快速版本:

      button.autoPinEdge(toSuperviewEdge: .left, withInset: 15)
      button.autoPinEdge(toSuperviewEdge: .right, withInset: 15)
      button.autoSetDimension(.height, toSize: 46)
      button.autoAlignAxis(.vertical, toSameAxisOf:  contentView)
      
      containerView.autoAlignAxis(toSuperviewAxis: .horizontal)
      containerView.autoAlignAxis(toSuperviewAxis: .vertical)
      
      iconImageView.autoPinEdge(.left, to: .left, of: containerView)
      iconImageView.autoAlignAxis(toSuperviewAxis: .horizontal)
      
      label.autoPinEdge(.right, to: .right, of: containerView)
      label.autoAlignAxis(toSuperviewAxis: .horizontal)
      label.autoPinEdge(.left, to: .right, of: iconImageView, withOffset: 10.0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        相关资源
        最近更新 更多