2017年3月20日 星期一

使用相冊的服務



重點是一定要加這兩個  UINavigationControllerDelegate 和  UIImagePickerControllerDelegate


class ViewController: UIViewController, UINavigationControllerDelegate,UIImagePickerControllerDelegate {



當按下button

先初始化一個   imagePickerController

設置  imagePickerController.delegate = self

然後選擇媒體type     imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary

接下來就是present



 @IBAction func importImage(_ sender: Any) {
        
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePickerController.allowsEditing = false
        self.present(imagePickerController, animated: true, completion: nil)
        

    }

然後記得在 info.plist 裡面加入權限要求



就可以執行了

接下來是要使用選到的相片


 @IBOutlet weak var imageview: UIImageView!


實作這個function...

去找   info[UIImagePickerControllerOriginalImage].. 然後把他轉型成UIImage...

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
            imageview.image = image
        }else{
            print("couldn't find image")
        }
        
        self.dismiss(animated: true, completion: nil)
    }







沒有留言:

張貼留言