2017-11-02 3 views
0

デバイスが風景に肖像画から回転させると、ビューの幅制約が更新されますが、デバイスが縦向きに横から回転させたときには更新されませんスウィフトデバイスの向きに応じて制約を変更

私のコード:

override func viewDidLoad() { 
    super.viewDidLoad() 
    theView.translatesAutoresizingMaskIntoConstraints = false 
    theView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true 
    theView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true 
    theView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true 
    theView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true 
    } 

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 

装置は、第1の風景に肖像画から回転される「theView」幅は、ビュー幅から回転

if UIDevice.current.orientation.isLandscape { 
     theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50).isActive = true 

の50%を得ます横から縦に戻っても元の幅に戻らない

} else { 
     theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.00).isActive = true 
    } 
} 

ここで私がしようとしていることを示す画像です。

enter image description here

答えて

2

回転するときは、右のアンカー制約を無効にする必要があります。 NSLayoutAnchorクラスのconstraint方法は常に新しい、非アクティブな制約を返し

ので、あなたがアクティブにする制約への参照を維持する必要があります/を無効にします。

初期化は次のようになります。

override func viewDidLoad() { 
    super.viewDidLoad() 
    // ...   
    widthConstraint = theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50) 
    rightConstraint = theView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0) 
    rightConstraint.isActive = true 
} 

これらの参照を使用すると、willRotate:メソッドをこのように実装できます。

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { 
    if UIDevice.current.orientation.isLandscape { 
     rightConstraint.isActive = false 
     widthConstraint.isActive = true 
    } 
    else { 
     rightConstraint.isActive = true 
     widthConstraint.isActive = false 
    } 
} 

これは次のようになります。

Ilustration of the solution

+0

カミルは、風景では動作しますが、肖像画に回転させて幅〜100% – Nicoli

+0

@Nicoliが、私は私の答えを更新し復元されません。見てください。 –

+0

完璧に動作します。ありがとう@カミル – Nicoli

関連する問題