私は、適応的なレイアウトを純粋なコードで作成する(ストーリーボードは使用しない)ようにしています。レイアウトアンカーを使用して制約を設定し、traitCollectionDidChangeメソッドを使用して、さまざまな制約やその他のインターフェイス変更を変更します。 switchステートメントを使用して、対応するメソッドを対応する制約のセットで呼び出します。コードのサイズクラスを変更する(Swift)
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
case (.regular, .regular):
setupRegularRegular()
case (.compact, .compact):
setupCompactCompact()
case (.regular, .compact):
setupRegularCompact()
case (.compact, .regular):
setupCompactRegular()
default: break
}
}
テストのために、centerYAnchor.constraintという制約が1つだけ変更されました。肖像画では定数は、-150である風景の中に、私はそれがiPad用の50に変更することにしたい、私はiPhoneとiPadの間で切り替えるときにそれが正常に動作します0
bigLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -150).isActive = true
に定数を設定します。しかし、あなたは肖像画から風景にiPhoneの回転を開始すると、レイアウトシステムに障害が発生した、と言って:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x600000097890 UILabel:0x7fac02c08aa0'Main Label'.centerY == UIView:0x7fac02e0a950.centerY - 150 (active)>",
"<NSLayoutConstraint:0x604000097840 UILabel:0x7fac02c08aa0'Main Label'.centerY == UIView:0x7fac02e0a950.centerY + 50 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x604000097840 UILabel:0x7fac02c08aa0'Main Label'.centerY == UIView:0x7fac02e0a950.centerY + 50 (active)>
は、私が戻ってtrueに、その後の様々なメソッドをオーバーライドし、falseに制約ののisActiveプロパティを設定してみましたが、ということ助けてくれなかった。私は2,3日ウェブを検索しました。これまでの解決策はありません。だから私の質問は、デバイスを回転させるときに、実際にどのようにサイズクラスを適切に切り替えるのですか?他の方法や何かを無効にする必要がありますか?純粋なコードでの適応型レイアウトのためのより良いソリューションはありますか?アダプティブレイアウト/サイズクラス/レイアウトアンカーとコードの制約(ストーリーボードを使用しない)については、ベストプラクティスはありますか? 助けてくれてありがとう!
P.S.制約を設定する方法は以下のとおりです。
func setupCompactRegular() {
bigLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -150).isActive = true
}
func setupRegularCompact() {
bigLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 50).isActive = true
}
セットアップ方法のコードを表示します。実際に既存の制約を編集しているのですか、それとも追加の制約を作成していますか? – dan
ポストをメソッドで更新しました。 – Andrei