今天要來介紹的是UIImagePickerController,我們可用它來取得照片,可以從相簿或相機中取得。
首先在Info.plist中加入請求取用相機及相簿的描述
接下來回到ViewController.swift中,必須讓ViewController繼承UIImagePickerControllerDelegate
、UINavigationControllerDelegate
這兩項Delegate,接著初始化一個UIImagePickerController並在viewdidload()中做委任。
接著在ButtonAction中加入以下程式碼
@IBAction func choosePhoto(_ sender: UIButton) {
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true)
}
.photoLibrary
或.camera
。最後再利用present()顯示ImagePickerController。
在選擇完照片後要取得必須實作ImagePickerDelegate中的方法didFinishPickingMediaWithInfo
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// 取得照片
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageView.image = image
//取得照片後將imagePickercontroller dismiss
picker.dismiss(animated: true, completion: nil)
}