Swift 4
- 在info.plist添加
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>
- View Controller需要implement UIImagePickerControllerDelegate, UINavigationControllerDelegate这两个delegate
- 申明需要的IBOutlet组件和定义UIImagePickerController
- 把UIImagePickerController的delegate设为自己的ViewController
- 实现imagePickerController方法
import UIKit
// 2.
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
// 3.
@IBOutlet weak var inputImgBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func inputImageBtnPress(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
// 4.
imagePicker.delegate = self
// get full access, otherwise use .savedPhotosAlbum
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
// Starts up the UIImagePickerController
present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let selectedImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
imageView.image = selectedImage
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion:nil)
}
}
网友评论