iOS新手求助:Swift4实现照片库多选图片并存入图片数组
Hey there! As a fellow iOS dev who’s been right where you are, let me walk you through how to pick multiple images from the photo library and store them in an array using Swift 4. It’s totally doable with a few key steps—let’s dive in!
First off, you need to ask the user for permission to access their photo library, otherwise your app will crash when trying to open it. Here’s how:
- Open your
Info.plistfile. - Add a new key called
NSPhotoLibraryUsageDescription(you can also use the human-readable name "Privacy - Photo Library Usage Description"). - Set its value to a clear explanation of why you need access, like "We need access to your photos so you can select images for your project".
Next, let’s add the code to trigger the photo picker and store the selected images. First, declare an array to hold your selected images at the top of your ViewController:
var selectedImages: [UIImage] = []
Then, add a function to present the photo picker (you can call this from a button tap, for example):
func openPhotoLibrary() { let imagePicker = UIImagePickerController() imagePicker.sourceType = .photoLibrary // This is the key line for multiple selection! imagePicker.allowsMultipleSelection = true imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) }
Your ViewController needs to conform to UIImagePickerControllerDelegate and UINavigationControllerDelegate to handle the selection. Update your class declaration:
class YourViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // Your existing code here }
Now add the delegate methods to handle the selected images and cancel action. Note that in Swift 4, you need to mark these with @objc since they’re Objective-C compatible methods:
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Get the array of selected images if let selectedImagesArray = info[.selectedImages] as? [UIImage] { // Add them to your array (you can replace instead of appending if needed) selectedImages.append(contentsOf: selectedImagesArray) print("Selected \(selectedImages.count) images!") } // Dismiss the picker picker.dismiss(animated: true, completion: nil) } @objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) }
If you need higher-resolution images (the default UIImage from the picker might be compressed), you can use PHAsset to fetch the original image. But that’s a bit more advanced—for a beginner, the above code works perfectly for most use cases.
内容的提问来源于stack exchange,提问作者rachna sharma

