iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 16
0
Software Development

30 天上手 iOS App 開發系列 第 16

30 天上手 iOS App 開發 DAY 16

在前幾天有介紹到取用相簿或是取用相機利用ImagePickerController實作的方法,而今天要介紹到另一個非常實用的元件CollectionView,並結合之前教的取用照片做結合,儲存每張從相簿或相機所拍攝的照片。

首先先在StoryBoard裡先拉一個Button跟CollectionView出來,CollectionView內加入一個imageView。
https://ithelp.ithome.com.tw/upload/images/20180104/20107506XCNUM0hiMM.png

接下來新增一個CollectionViewCell,並把imageView連接進Cell當中。
https://ithelp.ithome.com.tw/upload/images/20180104/20107506TGzy4cMcqx.png
https://ithelp.ithome.com.tw/upload/images/20180104/20107506uf3hfPReCl.png

接著再StoryBoard內CollectionViewCell採用新增的Cell,並宣告一個CellID名稱。
https://ithelp.ithome.com.tw/upload/images/20180104/20107506DT7JG3mXiO.png
https://ithelp.ithome.com.tw/upload/images/20180104/20107506xj1XxYTayR.png

接下來看看程式碼部分的CollectionView怎麼建的
一開始先把CollectionView的Delegate,DataSource宣告出來並和之前一樣把ImagePickerController用到的protocol先打出來,接著宣告之後要在CollectionView內顯示照片的陣列,和宣告一個用來控制每個Cell間距的CGFloat變數,這邊宣告每個Cell間距為4。
https://ithelp.ithome.com.tw/upload/images/20180104/20107506Pk4LZcdhBi.png

接著像之前一樣實作ImagePickerController部分的Info.plist兩項敘述,利用AlertController選擇取用相簿或相機,並利用didFinishPickingMediaWithInfo這個method,存取之前宣告存圖片的陣列,並每當陣列新加一張照片後reload我們的CollectionView。
https://ithelp.ithome.com.tw/upload/images/20180104/2010750624E8AuccQR.png
https://ithelp.ithome.com.tw/upload/images/20180104/20107506fr5FSerSRp.png
https://ithelp.ithome.com.tw/upload/images/20180104/20107506cuIbYDSPNu.png

再來實作CollectionView部分,先宣告要使用的Items數量,這邊是使用上面宣告的imageAry陣列的數目。接著實作每個Cell所顯示的內容,這裡先宣告一個變數採用Cell的重用機制,並使用之前StoryBoard宣告的CellID,和CollectionViewCell這個UICollectionViewCell。
https://ithelp.ithome.com.tw/upload/images/20180104/201075060cZ1qojPp7.png

最後使用UICollectionViewDelegateFlowLayout的protocol使用其中的三個method。
第一個控制每個Cell的長、寬的大小,第二個宣告每個Cell的左右間距,第三個宣告每個Cell的上下間距。
https://ithelp.ithome.com.tw/upload/images/20180104/20107506C0N51oTYXi.png


上一篇
30 天上手 iOS App 開發 Day15
下一篇
30 天上手 iOS App 開發 DAY 17
系列文
30 天上手 iOS App 開發28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言