SlideShare a Scribd company logo
1 of 21
iOSレイアウト 制約=Constraints について
2016/12/3 TAKEMAEDENKI
1
注意
iOSに関する話なのに家にMACが無いのでスクショを取れません。
ホワイトボードを使用できれば良いな。
2
前提
Androidのような「レイアウト機能を持つコンテナ部品(LinearLayout)」などは存在しないのがiOS
のザ世界です。
つまり「俺が・・・俺達がレイアウタだ!」ということです。
3
用語
○View
UI部品の総称。クラスとしてはUIView。
○ViewController
いわゆる画面。クラスとしては UIViewController。Androidで言うとActivity。
ただ、ページャーやドロワーなど、同一画面内に複数存在可能なので、どちらかというとFragment
に近い。
○TableView
いわゆるリスト。AndroidではListView。
レイアウトカスタマイズが可能なものとして、継承元の CollectionView もある。
不可能な分便利になっている面がある。※具体的には高さ計算を軽くする方向の工夫が取り入れ
られている。
○セル=Cell
TableView/CollectionView のアイテム一つ一つ
4
用語2
○Auto Layout
部品自身、もしくは部品と部品の関係性の制約=Constraints の記述によりレイアウト計算を行う仕組み
○制約=Constraints
自身のサイズの値、子から親への位置を示すマージン、部品と部品の間のマージンなどを指定可能。
また指定値に対して「その値に一致」「その値以上(要は最小値指定)」「その値以下(要は最大値指定)」が可能。
○デリゲート
コールバック関数
○xib/nib (じぶ/にぶ)
iOSでのレイアウトのファイルの拡張子。Androidではレイアウトのxmlがそれに当たる。
xmlと異なり直接の手動編集は無理な感じ。
XCodeのインターフェースビルダーというGUIでのみ編集します。
今は xib。nib は古い表現。ただし、プログラム側での関連APIには nib の名前が使われたまま。
5
レイアウトを決める要因
A. 自身への力
View自身の幅、高さを固定する力。表示領域が決まっている写真や解像度が決まっているア
イコンなどでよく使う。
絶対値指定が主だが、幅高さ比率(アスペクト比)指定も可能。
また、「親の高さに対して50%」のような比率指定も可能。
※例えばフラグ判定によって表示しない部品は「高さのConstraintsを 0 にする」などの制御を
プログラム側で行う。
※組み込み系からの視点だと絶対値が多く、Web系からの視点だと比率指定が多い気がす
る。
6
B. 連続する部品に対する力
上から下に向かって並べるなどでのコントロールツリー上で兄弟となるView間のマージン指定が主。
マージン指定は基本的に絶対値のみ。
もしマージンを相対指定にしたい場合には「自身への固定の力」で示したような
「親/他部品の高さに対して50%」という高さをもつスペーサとなるViewを配置してマージンの代わりとする。
※要は“位置”に関してはセンタリング以外の相対指定が出来ないということ。
相対指定は(今のところ)幅高さに関してのみ可能。
C. 外側から内側への力
端末の画面サイズは「この中に配置する」という「範囲内に収める」という内向きの力。
ViewController内やコンテナ内にどう部品を収めるか。
左右上下に対して部品の端を収めれば良いので、イメージしやすく Constraints の指定も簡単。
子から親に対してマージンを設定するのが主。
D. 内側から外側への力
TextViewの文字列によって幅高さが可変する、画像によって幅高さが可変するなど。
イメージは出来ても実際に設定しようとするとどういう Constraints を指定すればよいか迷うもの。
関係する部品が多くなればなるほど難易度が高くなる。
7
E. TableView/CollectionView の仕様力
なぜ概念でなく具体的な部品なのか?
よく使うにもかかわらず最も面倒な力であるためである。
なぜ面倒か?
※以下は縦スクロール前提でTableViewにおける高さを話題にしていきます。
・TableView は「すべての子部品=セル の高さを合算しないと"内部の高さ"が判明しない」
・"内部の高さ"が判明しないと スクロール全体の高さが分からない
・つまり表示範囲外のセルに関してもセル高さ計算デリゲート関数は呼ばれる
・要はセル高さが可変だととても頭が痛くなる
上記条件を真っ当に満たそうとすると以下になる。
・すべてのセルのレイアウトを行ってその高さを合算する。
・セル高さが固定なら良いが、画像サイズや情報表示の有無、文字列の長さによって高さ可変する場合に
は一つ一つレイアウトしないと高さが決まらない。
可変な高さでもセルの数が少なければ良いが、高さ計算が複雑で1000件以上にもなるとパフォーマンスに
影響を及ぼす。
8
○さらに面倒さを増やす仕様力
・セル生成はデリゲート関数が呼ばれてセルを返す。
・セル高さはデリゲート関数が呼ばれてFloat値を返す。
・セル高さ返却デリゲート関数が呼ばれるのはセル生成デリゲート関数の前
( ゚д゚)
(つд⊂)ゴシゴシ
(;゚д゚)
(つд⊂)ゴシゴシ
_, ._
(;゚ Д゚) …?!
初めて知ったときには
「あ・・・ありのまま 今起こった事を話すぜ!・・・な、なにを言っているのか分からない
と思うが」
と思って髪が高さ方向に可変になりました。
なので
9
TableViewを使う前に言っておくッ!
おれは今やつの仕様をほんのちょっぴりだが体験した
い…いや…体験したというよりはまったく理解を超えていたのだが……
,. -‐'''''""¨¨¨ヽ
(.___,,,... -ァァフ| あ…ありのまま 今 起こった事を話すぜ!
|i i| }! }} //|
|l、{ j} /,,ィ//| 『おれは奴の前でセルを作っていると
i|:!ヾ、_ノ/ u {:}//ヘ 思ったらいつのまにか高さ計算をしていた』
|リ u' } ,ノ _,!V,ハ |
/´fト、_{ル{,ィ'eラ , タ人 な… 何を言ってるのか わからねーと思うが
/' ヾ|宀| {´,)⌒`/ |<ヽトiゝ おれも何をされたのかわからなかった…
,゙ / )ヽ iLレ u' | | ヾlトハ〉
|/_/ ハ !ニ⊇ '/:} V:::::ヽ 頭がどうにかなりそうだった…
// 二二二7'T'' /u' __ /:::::::/`ヽ
/'´r -―一ァ‐゙T´ '"´ /::::/-‐ \ 催眠術(Apple製品を神とするお布施)だとか超スピードだとか
/ // 广¨´ /' /:::::/´ ̄`ヽ ⌒ヽ そんなチャチなもんじゃあ 断じてねえ
ノ ' / ノ:::::`ー-、___/:::::// ヽ }
_/`丶 /:::::::::::::::::::::::::: ̄`ー-{:::... イ もっと恐ろしいものの片鱗を味わったぜ…
10
で、話すこと
TableViewで高さ可変のセルが組み合わさったときの具体的な解法を示したい。
11
高さ可変セル内における Constraints設
定時のポイント
XCodeのインターフェースビルダーでの作業です。
・上から下に向かって"のみ" Constraints を作っていく
・インターフェースビルダー上におけるセル自体の高さは下端が見えないくらい伸ばしてもOK
・セルのルートView(セルにとっての一番の親)の下端からのマージンの Constraints指定は作らない
その Constraints は高さ計算によってそれは無意味になるため。
無意味な Constraints指定を残すことはメンテナンス性を下げる(要はあとで見たとき「わけがわから
ないよ」となる)
・表示する最後の部品より下に、見えない部品として"BottomView"という下端を示すためだけの部品
を作っておく
12
「セル高さ返却デリゲート関数が呼ばれるのは
セル生成デリゲート関数の前」への対応
プログラム側です。
・セルクラスにセル高さ計算用関数を xibから読み込んで static に格納しておく。
・セル高さ計算のためだけのセルクラスのインスタンスをstaticで作って、それをセル高さ計算
用関数で利用する
・セル高さ返却デリゲート関数が呼ばれたときにはセルクラスに作った static なセル高さ計算
用関数を使用することで、セル生成デリゲート関数より前に高さ計算ができる。
13
セル高さ計算用関数の実装
プログラム側での実装です。
1. (引数で渡される)セルの幅を設定
2. (引数で渡される)情報に沿って部品の表示/非表示や文字列の設定などを行う
3. setNeedsLayout() と layoutIfNeeded() の呼び出しで(設定幅に従った高さ方向の)レイアウト
処理を行わせる
4. BottomViewのY座標を取得するとセルの高さが取れる
14
わかったけど「セル高さ計算のためだけのセルクラ
スのインスタンス」をわざわざつくらんくても良くね?
xibから読み込んで static で独立したセルインスタンスでなく、
TableViewを使ったセル生成関数で使用する dequeueReusableCellWithIdentifier() で作ったセ
ルを使えば良くね?
→NGです。
それは以下のTableViewの仕様からです。
・dequeueReusableCellWithIdentifier()は引数にインデックスを与えます。
・TableViewはセルを再利用する
つまり「再利用されて別のインデックスになっているはずのセル」
に対してセル高さ計算関数の「2. 情報設定」で中身を変えてしまう可能性があるためです。
15
「高さ計算複雑で1000件以上にもなるとパ
フォーマンスに影響を及ぼす」への対応
・計算した高さの結果を配列にでも覚えよう。
横になったときなどは配列リセットか横用の配列を持つなど。
でも初期表示の重さへの対処にはならない。。。
16
初期表示に関して
・最初は数十件だけ表示して時間差を付けてorスクロール時にTableViewへ append する。
reloadData だと最初からの計算が再度始まってしまうので append がオススメ。
・諦める
くるくるを出すなど。
諦めないのなら次に示す estimatedRowHeight や UITableViewAutomaticDimension がありま
す。
17
TableView って通常の高さ=RowHeight だけでなく、推定の高
さ=estimatedRowHeight のAPIも出来たよね?
固定高さなセルの TableView では estimated を使用すべきです。
「表示されない領域のセルに関しては estimated が使われてセル高さ返却デリゲート関数が呼
ばれない」
ということが発生して初期表示が軽くなります。
が、高さ可変なセルでは estimated は使うべきではありません。
使った場合「スクロールが飛ぶんだけど!?」が発生し(てい)ます。
※今の仕事のアプリで発生している。他社のバグだけど。
18
TableView ってセル高さ自動計算の
UITableViewAutomaticDimension のAPIも出来たよね
標準のセルクラス=UITableViewCell の標準の Text に文字列を入れる場合にはOKです。
が、カスタムレイアウトなセルの場合には辞めておいた方が無難です。
解法として示されている「sizeToFit() オーバーライドで高さを設定する」
を行ったとしても「セルの表示が欠ける」が発生しました。
また、表示欠けが発生しなかったとしても「スクロール時のカクつき」が発生します。
まぁ初期表示があまりにレイアウトで遅いなら、そのトレードオフにはなるかも。
19
その他
・セル高さ可変で estimatedRowHeight + UITableViewAutomaticDimension を使ってもっとラクに
or初期表示を速くできる。という解法があれば教えて下さい。なんでもしますから。
・AttributedString はリッチテキスト記載ができるStringですが「画像添付」や「インデント」も使え
たりするのでホント便利ですよ。別のラベル/ImageViewを作らなくて済みます。
まぁ AttributedString の方がラベルの高さ計算が遅くなりますが。。。
・XCode7のSwift2.2からXCode8のSwift3への変換で苦労をした人は僕と握手!
・ガルパンはいいぞ
20
以上、ご静聴ありがとう
ございました。
21

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

iOSレイアウト 制約=constraints について