AutoLayoutを始めたのが最近なので3周遅れぐらいでいろいろ調べている。暖かく見守っていただきたい。
2つのViewに関連をつけるときにtranslatesAutoresizingMaskIntoConstraintsの設定が片方だけtrueのときの挙動はどうなるか。
前提
ソースで書く。Storyboardは使わない。
UIViewとUIViewの組み合わせ
viewA : AutoLayoutがオフ
viewB : AutoLayoutがオン
とする。viewAが何かの方法でframeが確定したとき、関連付けられているviewBは意図する設定がされるのか?
結論
viewAもAnchorの値は有効。
viewAのAnchorが決定するので、関連付けられたviewBのAnchorを決定することができる。
コード
//testView1.translatesAutoresizingMaskIntoConstraints = false
testView1.frame = CGRect(x: 30.0, y: 50.0, width: 50.0, height: 50.0)
testView2.translatesAutoresizingMaskIntoConstraints = false
testView2.topAnchor.constraint(equalTo: testView1.topAnchor).isActive = true
testView2.leadingAnchor.constraint(equalTo: testView1.trailingAnchor, constant: 30.0).isActive = true
testView2.heightAnchor.constraint(equalTo: testView1.heightAnchor).isActive = true
testView2.widthAnchor.constraint(equalTo: testView1.widthAnchor).isActive = true
UIScrollViewとUIViewの組み合わせ
今回のメインイベントである。UIScrollViewとその中に入れたUIViewはどうなるか?
UIScrollViewがAutoLayoutオフ、UIViewがオンのとき
結論
意図したとおりになる。まあ、意図というのは私自身にしかわからない表現かもしれない。
UIScrollViewのcontentSizeは、中にあるUIViewのサイズに関連してAutoLayoutで指令可能ということである。UIScrollView自身はAutoLayoutオフなのであるが。
コード
//scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.frame = CGRect(x: 30.0, y: 200.0, width: 200.0, height: 200.0)
testView3.translatesAutoresizingMaskIntoConstraints = false
testView3.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 10.0).isActive = true
testView3.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 10.0).isActive = true
testView3.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -10.0).isActive = true
testView3.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -10.0).isActive = true
testView3.heightAnchor.constraint(equalToConstant: 400.0).isActive = true
testView3.widthAnchor.constraint(equalToConstant: 400.0).isActive = true
UIScrollViewがAutoLayoutオン、UIViewがオフのとき
結論
UIScrollViewの外枠はAutoLayoutで指令できるが、contentSizeはAutoLayoutを使えなかった。中のUIViewのサイズが決定すればAutoLayoutでcontentSizeが設定可能かなと思ったのだが。古典的に指定することになる。
コード
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 200.0).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30.0).isActive = true
scrollView.heightAnchor.constraint(equalToConstant: 200.0).isActive = true
scrollView.widthAnchor.constraint(equalToConstant: 200.0).isActive = true
//testView3.translatesAutoresizingMaskIntoConstraints = false
testView3.frame = CGRect(x: 10.0, y: 10.0, width: 400.0, height: 400.0)
scrollView.contentSize = CGSize(width: 420.0, height: 420.0)
何か間違いや、表現の中途半端さがあれば指摘してください。
追記
少し問題に遭遇したのでこの方法を検討しましたが、問題は別の方法で対応することにしたので、この方法は結局使いませんでした。