[iOS study] 搭配 UIImagePickerController 選照片

練習delegate, imagePickerController, AlertController

點選button後跳出由下而上彈出的選單視窗

@IBAction func ImageButton(_ sender: UIButton) {let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)let cameraAction = UIAlertAction(title: "開啟相機拍照", style: .default) { (_) in...}let libraryAction = UIAlertAction(title: "從相簿中選擇", style: .default) { (_) in...}let deleteAction = UIAlertAction(title: "刪除", style: .destructive) { (_) insender.setImage(UIImage(named: "user"), for: .normal)}let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)controller.addAction(cameraAction)controller.addAction(libraryAction)controller.addAction(deleteAction)controller.addAction(cancelAction)present(controller, animated: true, completion: nil)}

從相簿中選擇照片

func photopicker(){let photoController = UIImagePickerController()photoController.delegate = selfphotoController.sourceType = .photoLibrarypresent(photoController, animated: true, completion: nil)}@IBAction func ImageButton(_ sender: UIButton) {
...
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {let image = info[.originalImage] as? UIImagebuttonImage.setImage(image, for: .normal)dismiss(animated: true, completion: nil)}

開啟相機功能,無法模擬器測試,但是我的iphone版本跟xcode版本無法測試......(只好這次先展示相簿就好,改天再試相機)

github:

--

--

Yolanda H.
彼得潘的 Swift iOS / Flutter App 開發教室

悠琅妲之愛梯熙緹推敲推敲潑墨坊 { iOS App | website SEO | Python | Aroma | Zumba | Chinese Poems | Tabletop game }