【问题标题】:Updating constraints on orientation change更新方向变化的约束
【发布时间】:2019-01-01 10:32:35
【问题描述】:

下面是纵向模式的视图(图 1)和我想显示的横向视图(图 2)。我面临着在横向中正确显示的问题。

图 1:

我在情节提要中有设置约束。

greenView: top: 0, leading: 0, trailing: 0, width: equal to superview.width, height: equal to superview.height/2

图片2: 我尝试修改约束,但是当我将设备转为横向时,greenView 变成了屏幕的 1/4。下面是代码。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        greenView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50).isActive = true
        greenView.heightAnchor.constraint(equalToConstant: 0).isActive = true
    } else {
    }
}

【问题讨论】:

  • 仅供参考,您需要致电super.viewWillTransition

标签: swift autolayout orientation adaptive-layout


【解决方案1】:

不用为此问题创建约束而头疼,而是将两个视图都插入到 UIStackView (vertical) 中,如果方向是 isLandscape,则在 viewWillTransition 内部将轴更改为水平

加上这些约束

greenView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50).isActive = true
greenView.heightAnchor.constraint(equalToConstant: 0).isActive = true

会产生冲突,因为旧的没有被删除

//

func shared () {

     if UIDevice.current.orientation == .portrait {

         self.stView.axis = .vertical
     }
     else {

         self.stView.axis = .horizontal 
     }

 }

viewDidLoad&viewWillTransition中调用上述方法

【讨论】:

  • 让我通过添加 UIStackView 来检查。
  • UIStackView 可以解决问题,但是当我根据高度而不是宽度将其拆分为两半时。任何建议。
【解决方案2】:

isActive 标志是被高度误解的选项。该标志不会改变约束的状态,它会完全添加或删除约束。

greenView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50).isActive = true
greenView.heightAnchor.constraint(equalToConstant: 0).isActive = true

上面的代码会在你的视图上添加多个约束。每次你旋转你的设备一个新的宽度,高度约束被添加到你的视图中,这将导致你的视图有多个高度和宽度约束。要添加/删除相同的约束,请存储其引用,然后在其上使用 isActive

我不确定您为什么将高度限制设置为 0?

现在来做你想做的事。我可以想到两种方法

第一种方法

除了故事板中现有的约束之外,再添加两个约束,但保持它们的优先级较低(

1. greenView.bottom = safeArea.bottom
2. greenView.width = superView.width/2

制作greenView.height = superview.height/2 and greenView.trailing = superView.trailing 的IBOutlet。 出口应该是那些具有高优先级的约束确保您的 Outlets 不弱,否则当您设置 isActive false 时,他们的 outlet 将变为 nil。现在您所要做的就是在设备更改为横向模式时进行设置:

highPriorityGreenViewConstraint.isActive = false
highPriorityHeightConstraint.isActive = false

第二种方法

使用尺寸等级来设置约束。所有尺寸等级都提到了here

示例 - 仅为 compact width compact height 大小类安装 greenView.bottom = safeArea.bottom,greenView.width = superView.width/2 约束。您将不得不在这种方法中施加更多限制,因为即使在 iPhone 型号之间横向尺寸等级也不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2016-04-17
    相关资源
    最近更新 更多