はじめに
Auto Layoutで制約を設定した際にでるログ「[LayoutConstraints] Unable to simultaneously satisfy constraints.」についてのメモ、備忘録です。
エラーメッセージの意味
まず、エラーメッセージです
[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.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
和訳です
[LayoutConstraints] 制約を同時に満たすことができません。
おそらく、以下のリストにある制約のうち少なくとも1つは、あなたが望まないものでしょう。
これを試してみてください:
(1)各制約を見て、どれが期待しないものかを突き止める;
(2) 不要な制約を追加したコードを見つけ、それを修正する。
(注: 理解できないNSAutoresizingMaskLayoutConstraintsが表示された場合は、UIViewプロパティtranslatesAutoresizingMaskIntoConstraintsのドキュメントを参照してください。)
原因
このエラーが起こる原因は、主に以下の2つです。
不適切な制約が設定されている
Viewのサイズが設定されていない、または不適切なサイズになっている
解決方法
では、このエラーを解決する方法についてです
制約の設定を見直す
まず、制約の設定を見直して、矛盾がないか確認してみます。特に、制約の優先度が設定されている場合は、制約同士が競合することがあるので、優先度を適切に設定することが重要です。
Viewのサイズを設定する
Viewのサイズが設定されていない場合はサイズを明示的に設定することが必要です。
具体的には、Viewに対して適切な制約を設定して、Viewのサイズを固定することが必要です。また、Viewが持つ要素(例えば、ImageViewやLabelなど)のサイズも、適切に設定する必要があります。
translatesAutoresizingMaskIntoConstraintsをfalseにする
Auto Layoutで制約を設定する際に、UIViewのtranslatesAutoresizingMaskIntoConstraintsプロパティがtrueに設定されている場合、制約の設定が上手くいかないです。そのため、制約を設定する前にtranslatesAutoresizingMaskIntoConstraintsプロパティをfalseに設定します。
例えば、以下のように設定します。
view.translatesAutoresizingMaskIntoConstraints = false
おわりに
私の場合はコードで制約をつけていてtranslatesAutoresizingMaskIntoConstraints = falseにし忘れていたが原因でした!
参考記事
https://wayohoo.com/article/6203
https://teratail.com/questions/46783
https://md.hatenablog.com/entry/2014/09/24/205505