iT邦幫忙

2021 iThome 鐵人賽

DAY 30
0
Mobile Development

ios 的小小實驗室 !系列 第 30

DAY 30『 從相簿選取照片( 有裁剪照片功能 ) 』ImagePicker - Part2

  • 分享至 

  • xImage
  •  

在 @IBAction 裡

  1. 令 vc 為 UIImagePickerController
    let vc = UIImagePickerController()
  2. 新增相簿權限
    vc.sourceType = .photoLibrary // 相簿
  3. 設定委任
    vc.delegate = self
  4. 允許用戶編輯選定的圖像或影像
    vc.allowsEditing = true
  5. 設定跳頁
    present(vc, animated: true)

到這邊會報錯是正常的,因為沒給它 UIImagePickerControllerDelegate
因此在專案裡用 extension 去寫委任

extension MainVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage") ] as? UIImage{
            imageView.image = image
        }
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}

附上完整程式碼

import UIKit

class MainVC: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    @IBAction func didTapButton(_:UIButton) {
        let vc = UIImagePickerController()
        vc.sourceType = .photoLibrary
        vc.delegate = self
        vc.allowsEditing = true
        present(vc, animated: true)
    }
}

extension MainVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage") ] as? UIImage{
            imageView.image = image
        }
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}

這樣就完成從相簿選取照片的實作了!


#完賽心得

13th鐵人賽到今天完賽了,終於完成連續30天的自我挑戰!透過鐵人賽,讓自己從最基本的說明介紹開始,更扎實地打好基本功,也更了解那些官方文件未提及的面向。這30天記錄了使用 swift 開發實作的過程,希望自己在完賽後,也能持續使用 swift 開發更多實作。感謝各位邦友收看!


上一篇
DAY 29『 從相簿選取照片( 有裁剪照片功能 ) 』ImagePicker - Part1
系列文
ios 的小小實驗室 !30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言