Unified Contacts

16 September, 2014

Using Image Set with Universal Storyboard

In universal storyboard, you can define a UIImageView for size classes of Any Any (Width Height). Therefore, code for this UIImageView will be effective in both iPad and iPhone. That's why universal storyboard is powerful and convenient. But sometimes, the image size for iPad is different from that for iPhone. In this case, image set can help you.

1. Go to "Images.xcassets" in your project. Click "+" then choose "New Image Set".


2. Rename the new image set to whatever you want.


3. In this example, I prepared 2 sets of image. The green set is for regular size (300x300) and the blue set is for compact size (150x150). By default, there is one set for any any. Now, we are going to add another set for "compact width any height". On the right hand side, change the width to "Any & Compact". Then drag the green set to any any, and drag the blue set to compact any.


4. Back to storyboard, add a UIImageView and set the source as the name of image set we just created.


5. One important thing is we have to give the position constraint to the UIImageView, otherwise it won't resize based on the image for compact size. Here, we add 2 constraints that align horizontal and vertical center to superview.


6. Let's preview before we actually run. Enable the assistant editor. Click the root of the path then choose Main.storyboard in the Preview submenu.


7. Add both iPad and iPhone to the preview by clicking the "+" on the bottom left of the assistant editor.


8. Cool!! Now we can see iOS select the correct image according to the size class.


9. Not only in preview, when you change the size class in storyboard. The image is also changed based on the size class.


This help developer to reduce number of lines, and make the universal app more consistent.



在universal storyboard, 你可以定義UIImageView的size class為Any Any (Width Height). 這樣關於UIImageView的程式碼會在iPad及iPhone都有效. 這就是為何universal storyboard如此強大. 但有時候圖片尺吋在iPad和iPhone上是不一樣的. 這個情況下image set可以幫到你.
1. 在project裡, 選"Images.xcassets". 點選"+"後選"New Image Set".


2. 為剛新增的image set改名


3. 在這範例, 我準備了2組圖片. 綠色是給regular size (300x300) 而藍色是給compact size (150x150). 預設, 只有一組any any. 現在我們要新增一組給"compact width any height". 在右手邊, 把width改成"Any & Compact". 然後把綠色一組拉到any any, 把藍色一組拉到compact any.


4. 回到storyboard, 新增一個UIImageView及把來源設定為剛剛創建的image set.


5. 一個很重要的是我們要給UIImageView位置constraint, 否則它不會按compact size的圖片改變尺吋. 這裡我們加2個contraint, 分別是對superview水平置中及垂直置中.


6. 運行前先來預覧, 開啟assistant editor. 點路徑的最頂層. 然後在Preview子選單選擇Main.storyboard.


7. 新增iPad及iPhone到preview, 在assistant editor點左下角的"+".

8. Cool!! 現在我們可以看到iOS跟據size class撰擇正確的圖片.


9. 不單的preview, 當你把storyboard的size class更改. 圖片亦會跟據size class改變.


這幫助開發者減少得多程式碼, 還令universal app便一致.

No comments:

Post a Comment