LoginSignup
9
8

More than 5 years have passed since last update.

UIStackViewのトルツメWarning対応

Posted at

概要

iOSのUIStackViewを使ってトルツメ(空いた部分を詰めるレイアウト)を行う際に発生したWarningとその対応方法

実装内容

storyboard
Storyboard上の定義は上記のような形。
Button2をhiddenすることで、Button1とButton3のみの表示にしつつ隙間をつめる。

Warning

Button2をhiddenしたタイミングで下記のwarningがコンソールに出力された。

console
[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:0x61000009ae00 UIButton:0x7ff580d07320'Button2'.height == 40   (active)>",
    "<NSLayoutConstraint:0x6000000998c0 'UISV-hiding' UIButton:0x7ff580d07320'Button2'.height == 0   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x61000009ae00 UIButton:0x7ff580d07320'Button2'.height == 40   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

原因と対応方法

[原因]

warning内容にも記載されている通りButton2に設定しているHeight=40制約と、Button2をHiddenしたことによってHeight=0になるという状態に矛盾が発生していたため。

[対応方法]

制約の矛盾を解除すればよい。
ボタンに設定したHeight=40の制約のPriorityを下げる(999など)
Constrain.png

おわりに

入り組んだレイアウトを作成している際にぶち当たり、妙にハマってしまいました。
今回はContent Hugging PriorityContent Compression Resistance Priorityを使いませんでしたが、
この辺りをきっちりと理解すれば、とても低コストでレイアウト作成や変更を行うことが出来るようになりますね。

UIStackViewを触るに当たって、下記の記事がとても参考になりました。ありがとうございます。
StackViewを賢く使ってらくちんAutoLayout

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8