在 @IBAction 裡
let vc = UIImagePickerController()
vc.sourceType = .photoLibrary // 相簿
vc.delegate = self
vc.allowsEditing = true
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 開發更多實作。感謝各位邦友收看!