UIScrollView 如何正確使用 AutoLayout?

UIScrollView 是 iOS 中相當常用的 View,而海芋每次在開發 iOS 畫面時,如果有使用 AutoLayout,常常在畫面遇到紅字,讓海芋每次都非常困擾,每次解都找了一些資料,非常花時間。而海芋在這裡也將解法分享給大家,供有開發 iOS 的讀者做一個參考。

ios-scrollview

 

Step 1.
首先,先在畫面加入 Scroll View。
ios-scrollview-1

Step 2.
接著,將 Scroll View 對齊外層的 View。
ios-scrollview-2

 

Step 3.
再來,在 Scroll View 的內容再加入一層 View,而這個 View 稱為 Scroll View 的 Content View,目的是要讓 Scroll View 能夠捲動,也是這個 Scroll View 中的實際內容。
ios-scrollview-3

 

Step 4.
再來,將 Scroll View 中的 Content View 對 Scroll View 進行對齊。
ios-scrollview-4

 

Step 5.
對齊之後,你會發現有兩種錯誤, 分別是 Scroll View Need Constraints for x position/width 和 Scroll View  Need Constraints for y position/height。原因是因為 Content View 裡頭沒有畫面,所以不知道 Content View 的高度和寬度,以致於 Scroll View 不知道捲動的範圍。
ios-scrollview-5

 

Step 6.
而接下來,我們在 Scroll View 的 Content View 加入了「綠色」和「紅色」的 View,並且分別對這兩個 View 指定了高度,但是還是有紅字。
ios-scrollview-6

 

Step 7.
這時的文字就是 Scroll View Need Constraints for x position/width 。
ios-scrollview-7

 

Step 8.
要解決這個問題很簡單,只要將 Scroll View 中的 Content View 對齊 Scroll View 的中間就好。
ios-scrollview-8

 

Step 9.
而在 Content View 加入了 Align Center X to ScrollView,問題就解決了,ScrollView 就順利畫出來啦。
ios-scrollview-9

 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments