【问题标题】:Custom Aspect Ratio with AutoLayout使用自动布局自定义纵横比
【发布时间】:2012-09-20 10:25:40
【问题描述】:

假设我有一个 UIView,其中包含一个必须为 4:3 的子 UIView。我想在代码中使用 AutoLayout 来解决这个问题。

我一直在努力使用 AutoLayout,但我还没有弄清楚如何做到这一点。

你知道如何解决这个问题吗?

非常感谢。

我附上一张图片来更好地解释我的意思。 http://d.pr/i/d0Oc

【问题讨论】:

    标签: objective-c uiview uikit ios6 autolayout


    【解决方案1】:

    我想通了。

    //Given a childView... 
    NSLayoutConstraint *constraint =[NSLayoutConstraint
                               constraintWithItem:childView
                               attribute:NSLayoutAttributeWidth
                               relatedBy:NSLayoutRelationEqual
                               toItem:childView
                               attribute:NSLayoutAttributeHeight
                               multiplier:4.0/3.0 //Aspect ratio: 4*height = 3*width
                               constant:0.0f];
                [childView addConstraint:constraint];
    

    【讨论】:

    • 界面生成器也可以这样做吗?
    • 是的,从 Xcode 6 开始!在 Pin Tool 中,现在有一个 Aspect 选项。
    • 我认为它需要交换 NSLayoutAttributeHeight 和 NSLayoutAttributeWidth。现在它说的是 3:4 而不是 4:3。
    • 另外,这里要补充一点,约束的乘数一旦创建就无法更改——乘数属性是只读的。即使使用关键路径也无法更改乘数。继续的方法是删除手头的约束并使用新的乘数重新创建它。
    【解决方案2】:

    这是 Swift 3 的语法:

    NSLayoutConstraint(
      item: item,
      attribute: .width,
      relatedBy: .equal,
      toItem: item,
      attribute: .height,
      multiplier: width / height,
      constant: 0)
    

    【讨论】:

      【解决方案3】:

      我已经尝试了以上所有答案,但没有奏效,这是我使用 swift 3 的解决方案:

      let newConstraint = NSLayoutConstraint(item: yourView, attribute: .width, relatedBy: .equal, toItem: yourView, attribute: .height, multiplier: 560.0/315.0, constant: 0)
      yourView.addConstraint(newConstraint)
      NSLayoutConstraint.activate([newConstraint])  
      NSLayoutConstraint.deactivate(yourView.constraints)
      yourView.layoutIfNeeded()
      

      【讨论】:

        猜你喜欢
        • 2017-01-20
        • 2020-01-16
        • 2014-10-23
        • 2015-02-28
        • 2015-07-01
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多