UIImagePickerController 三種 Types
UIImagePickerController 用來選取相簿的照片、影片、或是使用相機拍照。
UIImagePickerController 有三種 Types 設定如何選擇圖片:
- UIImagePickerController.sourceType.photoLibrary (從圖庫取得照片)
- UIImagePickerController.sourceType.camera (使用相機拍攝取得照片)
- UIImagePickerController.sourceType.savedPhotosAlbum (相簿取得照片)
設定完 Types,利用 present 的方式呈現。
如何顯示從相簿中挑選照片
一開始需要讀取使用者手機內的相簿,因此需要設定可以使用相簿的權限,
在Info中新增一個 Privacy — Photo Library Usage Description
進入程式碼部分~首先設定 UIImagePickerController 的 delegate。
加入 UIImagePickerControllerDelegate, UINavigationControllerDelegate
因為 delegate 的型別,所以 ViewController 要同時遵守 protocol UIImagePickerControllerDelegate 還有 UINavigationControllerDelegate!
UIImagePickerControllerDelegate (處理選取照片後的function)
UINavigationControllerDelegate (開啟相機或選取照片時畫面跳轉時需要的)
接著在 storyboard 放入 UIImageView 顯示圖片,還有一個按鈕來選擇照片。
按鈕的function
使用UIImagePickerController.sourceType.savedPhotosAlbum (相簿取得照片)
- 先創立 UIImagePickerController()
- 接著設置 .sourceType 這裏使用.photoLibrary (從圖庫取得照片)
- 再來 .delegate是要引用此方法必須的
- 最後 present 這個 controller 也就是 UIImagePickerController()
接著當使用者拍照或選照片後,會呼叫 UIImagePickerControllerDelegate 中function imagePickerController(_:didFinishPickingMediaWithInfo:)
可以從參數 info 拿到圖片的資料,info 的型別是 dictionary,傳入 key 中。而 info[.originalImage]可得到圖片。所以我們從function 的 info 中拿取照片(info[.originalImage]) 把他轉型成 UIImage ,然後顯示在UIImageView上,最後要記得使用 dismiss ,在選擇之後把這個controller的收起來喔~~~
提醒!這個選取照片,模擬器無法執行喔,只能在實機上測試!
如何顯示使用手機相機拍照
接著我們嘗試開啟相機拍照,跟選照片一樣,需要使用開啟手機相機功能,因此需要設定同意使用相機拍照。在Info中新增Privacy — Camera Usage Description
程式碼部分,做法跟上面幾乎相同,只是在設置 .sourceType 這裡使用.camera (使用相機拍攝取得照片)
提醒!這個拍攝照片,模擬器無法執行喔,只能在實機上測試!
結合兩種選擇方式
最後我們來將這兩種選擇方式結合在一起吧!使用 UIAlertController 選擇。
使用 UIAlertController .actionSheet 選單方式 由下往上顯示
最後來看看執行結果啦~~~
提醒!模擬器無法執行喔,只能在實機上測試!
附上Github 連結