如何让用户用Swiftselect图片?

我正在用Swift编写我的第一个iOS应用程序(仅iPhone)。 主应用程序视图应该允许用户从照片库中select图像。

我已经find以下示例代码的ViewController.swift

class ViewController: UIImagePickerController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { var imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum imagePickerController.allowsEditing = true self.presentViewController(imagePickerController, animated: true, completion: { imageP in }) } func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) { let selectedImage : UIImage = image println(selectedImage) } } 

并具有以下视图控制器场景 –

 View Controller - Top Layout Guide - Bottom Layout Guide - View - Image View First Responder Exit 

但是当我启动应用程序时,只显示黑屏。 我做错了什么? 我find的另一个示例代码是在Objective-C中,它不帮助我。

如果您只想让用户使用UIImagePickerControllerselect图像,请使用以下代码:

 import UIKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet var chooseBuuton: UIButton! var imagePicker = UIImagePickerController() @IBAction func btnClicked() { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ print("Button capture") imagePicker.delegate = self imagePicker.sourceType = .savedPhotosAlbum; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){ self.dismiss(animated: true, completion: { () -> Void in }) imageView.image = image } } 

我会给你最好的理解代码挑选图像,请参阅此

 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { UIAlertAction in self.openCamera() } var gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default) { UIAlertAction in self.openGallary() } var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in } // Add the actions picker?.delegate = self alert.addAction(cameraAction) alert.addAction(gallaryAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { picker!.sourceType = UIImagePickerControllerSourceType.Camera self .presentViewController(picker!, animated: true, completion: nil) } else { let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"") alertWarning.show() } } func openGallary() { picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(picker!, animated: true, completion: nil) } //PickerView Delegate Methods func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { picker .dismissViewControllerAnimated(true, completion: nil) imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage } func imagePickerControllerDidCancel(picker: UIImagePickerController) { println("picker cancel.") } 

祝你今天愉快:-)

对于Swift 3

1-首先,您需要在info.plist中添加以下密钥

  <key>NSPhotoLibraryUsageDescription</key> <string>This app requires access to the photo library.</string> 

2-你的视图控制器需要符合以下协议UIImagePickerControllerDelegate,UINavigationControllerDelegate。

 class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {} 

3 – 需要声明你将用来绑定返回/select的图像的UIImage

  @IBOutlet weak var myImageView: UIImageView! @IBoutlet weak var upLoadImageBtn:UIImage! let imagePicker = UIImagePickerController() 

3-将pickerImage委托设置为您的ViewController

  imagePicker.delegate = self 

4-对于上传button,您将需要喜欢以下图像为了发动行动并显示imagePicker

 @IBAction func upLoadImageBtnPressed(_ sender: AnyObject) { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary /* The sourceType property wants a value of the enum named UIImagePickerControllerSourceType, which gives 3 options: UIImagePickerControllerSourceType.PhotoLibrary UIImagePickerControllerSourceType.Camera UIImagePickerControllerSourceType.SavedPhotosAlbum */ present(imagePicker, animated: true, completion: nil) } 

5-您的视图控制器需要实现图像选取器代表的委托方法

  // MARK: - ImagePicker Delegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { myImageView.contentMode = .scaleAspectFit myImageView.image = pickedImage } /* Swift Dictionary named “info”. We have to unpack it from there with a key asking for what media information we want. We just want the image, so that is what we ask for. For reference, the available options are: UIImagePickerControllerMediaType UIImagePickerControllerOriginalImage UIImagePickerControllerEditedImage UIImagePickerControllerCropRect UIImagePickerControllerMediaURL UIImagePickerControllerReferenceURL UIImagePickerControllerMediaMetadata */ dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion:nil) } 

祝你有美好的一天:)

  @IBAction func chooseProfilePicBtnClicked(sender: AnyObject) { let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { UIAlertAction in self.openCamera() } let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default) { UIAlertAction in self.openGallary() } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in } // Add the actions picker.delegate = self alert.addAction(cameraAction) alert.addAction(gallaryAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } func openCamera(){ if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){ picker.sourceType = UIImagePickerControllerSourceType.Camera self .presentViewController(picker, animated: true, completion: nil) }else{ let alert = UIAlertView() alert.title = "Warning" alert.message = "You don't have camera" alert.addButtonWithTitle("OK") alert.show() } } func openGallary(){ picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(picker, animated: true, completion: nil) } //MARK:UIImagePickerControllerDelegate func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){ picker .dismissViewControllerAnimated(true, completion: nil) imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage } func imagePickerControllerDidCancel(picker: UIImagePickerController){ print("picker cancel.") } 

做这个显示照片库图像的东西swift编码:

 var pkcrviewUI = UIImagePickerController() if UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { pkcrviewUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary pkcrviewUI.allowsEditing = true pkcrviewUI.delegate = self [self .presentViewController(pkcrviewUI, animated: true , completion: nil)] } 

我知道这是一个问题,但这里有一些非常简单的代码(大部分来自本教程 )对我来说很好:

 import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! var imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() self.imagePicker.delegate = self } @IBAction func loadImageButtonTapped(sender: AnyObject) { print("hey!") self.imagePicker.allowsEditing = false self.imagePicker.sourceType = .SavedPhotosAlbum self.presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { self.imageView.contentMode = .ScaleAspectFit self.imageView.image = pickedImage } dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.imagePicker = UIImagePickerController() dismissViewControllerAnimated(true, completion: nil) } 

当然,上面的答案解决了主要问题。

我在Swift 3.0中遇到了一个崩溃,同时启动了相册,因为Info.plist没有这些标志:

  1. 隐私 – 照片库使用说明 – > NSPhotoLibrary使用说明

  2. 隐私 – 相机使用说明 – > NSCameraUsageDescription

[ 截图[1]

如果您遇到类似问题,请添加它们。

谢谢 !

这里是一个简单的方法来做到这一点:

但首先你必须在info.plist中添加(Privacy – Photo Library Usage Description),并且你的viewController中应该有一个button和一个UIImageView。

然后创build一个UIImageView的出口(在这个代码中出口被称为myImage),以及button的动作(我称之为在我的代码中导入的动作)

 import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var myImage: UIImageView! @IBAction func importing(_ sender: Any) { let Picker = UIImagePickerController() Picker.delegate = self Picker.sourceType = .photoLibrary self.present(Picker, animated: true, completion: nil) Picker.allowsEditing = true Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)! } func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1 myImage.contentMode = .scaleAspectFit //2 myImage.image = chosenImage //3 dismiss(animated:true, completion: nil) //4 } } 

如果你不想有一个单独的button,那么这里是另一种方法。 在imageView本身上附加一个手势,在点击图像时,一个警报将popup两个选项。 您可以select从图库/照片库中select或取消提醒。

 import UIKit import CoreData class AddDetailsViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! var picker:UIImagePickerController? = UIImagePickerController() @IBAction func saveButton(sender: AnyObject) { let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext) let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext) person.image = UIImageJPEGRepresentation(imageView.image!, 1.0) //imageView.image do { try person.managedObjectContext?.save() //people.append(person) } catch let error as NSError { print("Could not save \(error)") } } override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AddDetailsViewController.tapGesture(_:))) imageView.addGestureRecognizer(tapGesture) imageView.userInteractionEnabled = true picker?.delegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tapGesture(gesture: UIGestureRecognizer) { let alert:UIAlertController = UIAlertController(title: "Profile Picture Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let gallaryAction = UIAlertAction(title: "Open Gallary", style: UIAlertActionStyle.Default) { UIAlertAction in self.openGallary() } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in self.cancel() } alert.addAction(gallaryAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } func openGallary() { picker!.allowsEditing = false picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary presentViewController(picker!, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.contentMode = .ScaleAspectFit imageView.image = pickedImage } dismissViewControllerAnimated(true, completion: nil) } func cancel(){ print("Cancel Clicked") } } 

添加更多的问题,实现了在CoreData中存储图像的逻辑。

点击button,打开Image Gallery,并在imageview swift 3.0中设置图像

添加三个委托UIImagePickerControllerDelegate,UIPopoverControllerDelegate,UINavigationControllerDelegate

 var picker:UIImagePickerController?=UIImagePickerController() @IBOutlet var imgPhoto: UIImageView! override func viewDidLoad() { super.viewDidLoad() picker?.delegate=self } @IBAction func btnAddPhotoClicked(_ sender: UIButton) { openGallary() } func openGallary() { picker!.allowsEditing = false picker!.sourceType = UIImagePickerControllerSourceType.photoLibrary present(picker!, animated: true, completion: nil) } //MARK:- ImagePicker Controller Delegate //MARK:- func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imgPhoto.contentMode = .scaleToFill imgPhoto.image = chosenImage } else{ print("Something went wrong") } self.dismiss(animated: true, completion: nil) } 

只是回答这里提到: info[UIImagePickerControllerEditedImage]可能是你想在大多数情况下使用的。

除此之外,这里的答案是全面的。

尝试这一个很容易..使用UIImagePickerControllerDelegate Pic图像

  @objc func masterAction(_ sender: UIButton) { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ print("Button capture") imagePicker.delegate = self imagePicker.sourceType = .savedPhotosAlbum; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } print("hello i'm touch \(sender.tag)") } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage { print("Get Image \(chosenImage)") ImageList.insert(chosenImage, at: 0) ArrayList.insert("", at: 0) Collection_Vw.reloadData() } else{ print("Something went wrong") } self.dismiss(animated: true, completion: nil) }