如何允许用户使用 Swift 选择图像?

Posted

技术标签:

【中文标题】如何允许用户使用 Swift 选择图像?【英文标题】:How to allow user to pick the image with Swift? 【发布时间】:2014-10-20 00:43:41 【问题描述】:

我正在使用 Swift 编写我的第一个 ios 应用程序(仅限 iPhone)。主应用程序视图应允许用户从照片库中选择图像。

我找到了以下 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

但是当我启动应用程序时,只显示黑屏。我做错了什么? 我发现的另一个 sample code 在 Objective-C 中,这对我没有帮助。

【问题讨论】:

一个问题可能是 didSselectRowAtIndePath 是 UITableViewDelegate 的委托调用。根据您的场景布局和代码,这里没有使用 tableview,并且您的 ViewController 不是 UITableViewDelegate。也许 start 将是一个可以工作的空白项目,并添加一个按钮并从按钮按下触发您的代码。 @LA_ 我不明白为什么这里会涉及到tableView函数? 它工作正常并经过良好测试只需转到:***.com/questions/41717115/… 请看这个,theswiftdev.com/… 【参考方案1】:

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

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

            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 中删除 @IBaction 并在您想在 viewDidLoad 中说或任何时候调用它时调用 func 谢谢。它说Attempt to present <UIImagePickerController: 0x7fdb84029800> on <MyApp.ViewController: 0x7fdb838360a0> whose view is not in the window hierarchy!。我应该在场景中添加一些东西吗? 我赞成 bc 这真的很有帮助。只需将 NSDictionary 更改为 [NSObject: AnyObject] 并且效果很好! @DekelMaman 在审核队列中有一个建议的编辑使其成为 Swift3,但 it was of poor quality,所以我拒绝了它并进行了适当的编辑以避免更多建议【参考方案2】:

swift 4 的完整复制粘贴工作图像选择器基于 @user3182143 答案:

import Foundation
import UIKit


class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

    var picker = UIImagePickerController();
    var alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
    var viewController: UIViewController?
    var pickImageCallback : ((UIImage) -> ())?;
    
    override init()
        super.init()
        let cameraAction = UIAlertAction(title: "Camera", style: .default)
            UIAlertAction in
            self.openCamera()
        
        let galleryAction = UIAlertAction(title: "Gallery", style: .default)
            UIAlertAction in
            self.openGallery()
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
            UIAlertAction in
        

        // Add the actions
        picker.delegate = self
        alert.addAction(cameraAction)
        alert.addAction(galleryAction)
        alert.addAction(cancelAction)
    

    func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) 
        pickImageCallback = callback;
        self.viewController = viewController;

        alert.popoverPresentationController?.sourceView = self.viewController!.view

        viewController.present(alert, animated: true, completion: nil)
    
    func openCamera()
        alert.dismiss(animated: true, completion: nil)
        if(UIImagePickerController .isSourceTypeAvailable(.camera))
            picker.sourceType = .camera
            self.viewController!.present(picker, animated: true, completion: nil)
         else 
            let alertController: UIAlertController = 
                let controller = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: .default)
                controller.addAction(action)
                return controller
            ()
            viewController?.present(alertController, animated: true)
        
    
    func openGallery()
        alert.dismiss(animated: true, completion: nil)
        picker.sourceType = .photoLibrary
        self.viewController!.present(picker, animated: true, completion: nil)
    

    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) 
        picker.dismiss(animated: true, completion: nil)
    
    //for swift below 4.2
    //func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
    //    picker.dismiss(animated: true, completion: nil)
    //    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    //    pickImageCallback?(image)
    //
    
    // For Swift 4.2+
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[.originalImage] as? UIImage else 
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        
        pickImageCallback?(image)
    



    @objc func imagePickerController(_ picker: UIImagePickerController, pickedImage: UIImage?) 
    


像这样从您的视图控制器调用它:

    ImagePickerManager().pickImage(self) image in
        //here is the image
    

另外不要忘记在您的info.plist 中包含以下键:

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

【讨论】:

必须用这个替换 func imagePickerController 才能使其工作。谢谢! func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage pickImageCallback?(image) picker.dismiss(animated: true, completion: nil) 'NSInternalInconsistencyException', reason: 'UIAlertController can only have one action with a style of UIAlertActionStyleCancel' 我在上面的代码中遇到了这个错误。 我添加了以下代码来解决这个问题: if alert.actions.count > 0 // 取消后再次调用警报 self.present(alert, animated: true, completion: nil) else alert.addAction(cameraAction) alert.addAction(galleryAction) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) @Ing.Ron addActions 只需要设置一次,因此它们应该放在 init 方法中——我已经更新了代码。如果您对此有任何问题,请告诉我 @vir us:非常感谢您的快速响应!就我而言,我将您的 init() 代码放在 viewDidLoad() 中,这对我来说很好!【参考方案3】:

对于 Swift 3:

    首先,您需要在 info.plist 中添加以下键:

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

    您的视图控制器需要符合以下协议: UIImagePickerControllerDelegateUINavigationControllerDelegate

    class ImagePickerViewController:  UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate 
    

    您需要声明将用于绑定返回/选定图像的 UIImage:

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

    将 pickerImage 委托设置为您的 ViewController:

    imagePicker.delegate = self
    

    对于上传按钮,您需要链接到以下图片才能触发操作并显示图片选择器:

    @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)
    
    
    

    您的视图控制器需要为图像选择器委托实现委托方法:

    // 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)
    
    

【讨论】:

【参考方案4】:

我会给你最好的理解编码来挑选图像,参考这个

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.")

祝你有美好的一天:-)

【讨论】:

【参考方案5】:

在 Swift 5 中你必须这样做

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

    @IBOutlet var imageView: UIImageView!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() 
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    

    @IBAction func setPicture(_ sender: Any) 
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary)
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false

            present(imagePicker, animated: true, completion: nil)
        
    

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
        picker.dismiss(animated: true, completion: nil)
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage 
            imageView.image = image
        

    





【讨论】:

【参考方案6】:
    @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.")

【讨论】:

【参考方案7】:

XCODE 10.1 / SWIFT 4.2:

    添加所需权限(其他提及)

    将此类添加到您的视图中:


    import UIKit

    import Photos

    import Foundation

class UploadImageViewController: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate 

        @IBOutlet weak var imgView: UIImageView!

        let imagePicker = UIImagePickerController()

        override func viewDidLoad() 

            super.viewDidLoad()

            checkPermission()

            imagePicker.delegate = self
            imagePicker.allowsEditing = false
            imagePicker.sourceType = .photoLibrary
        

        @IBAction func btnSetProfileImageClickedCamera(_ sender: UIButton) 
        

        @IBAction func btnSetProfileImageClickedFromGallery(_ sender: UIButton) 
            self.selectPhotoFromGallery()
        

        func selectPhotoFromGallery() 
            self.present(imagePicker, animated: true, completion: nil)
        

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 

            if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage 
                    self.imgView.contentMode = .scaleAspectFit
                    self.imgView.image = pickedImage
                

            dismiss(animated: true, completion: nil)
        


        func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
            print("cancel is clicked")
        


        func checkPermission() 
            let photoAuthorizationStatus = phphotoLibrary.authorizationStatus()
            switch photoAuthorizationStatus 
            case .authorized:
                print("Access is granted by user")
            case .notDetermined:
                PHPhotoLibrary.requestAuthorization(
                    (newStatus) in
                    print("status is \(newStatus)")
                    if newStatus ==  PHAuthorizationStatus.authorized 
                        /* do stuff here */
                        print("success")
                    
                )
                print("It is not determined until now")
            case .restricted:
                // same same
                print("User do not have access to photo album.")
            case .denied:
                // same same
                print("User has denied the permission.")
            
        
    

【讨论】:

【参考方案8】:

做这些东西来显示照片库图像快速编码:

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)]
        

【讨论】:

【参考方案9】:

我知道这个问题已经有一年的历史了,但这里有一些非常简单的代码(主要来自 this tutorial)对我来说效果很好:

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)

【讨论】:

可以找到比我引用的更深入的教程here【参考方案10】:

对于 Swift 4 这段代码对我有用!

import UIKit


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate 

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() 
        super.viewDidLoad()
        imagePicker.delegate = self
    
    @IBAction func btnClicked() 

    if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) 
    
        print("Button capture")
        imagePicker.sourceType = .savedPhotosAlbum;
        imagePicker.allowsEditing = false

        self.present(imagePicker, animated: true, completion: nil)
        
    

  @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    imageView.image = chosenImage

    dismiss(animated: true, completion: nil)
    

【讨论】:

【参考方案11】:

Xcode 10、Swift 4.2

下面是一个略微优化的实现版本。 这是在 Swift 4.2 中,我也测试过。

您可以在此处查看 ViewController 的完整代码。 请注意,您还必须在情节提要中定义和连接一个 IBOutlet (imageView) 和 IBAction (didTapOnChooseImageButton)。希望这会有所帮助。

import UIKit

class ImagePickViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate 

var imagePicker = UIImagePickerController()
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() 
    super.viewDidLoad()
    // Do any additional setup after loading the view.


@IBAction func didTapOnChooseImageButton(_ sender: Any) 
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertAction.Style.default) 
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.camera)
    
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertAction.Style.default) 
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.photoLibrary)
    
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) 
        UIAlertAction in
    

    // Add the actions
    imagePicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.present(alert, animated: true, completion: nil)


func openCamera(_ sourceType: UIImagePickerController.SourceType) 
    imagePicker.sourceType = sourceType
    self.present(imagePicker, animated: true, completion: nil)


//MARK:UIImagePickerControllerDelegate

func imagePickerController(_ picker: UIImagePickerController,
                                    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
    imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    imagePicker.dismiss(animated: true, completion: nil)


func imagePickerControllerDidCancel(_ picker: UIImagePickerController) 
    print("imagePickerController cancel")



【讨论】:

欢迎来到 SO Nish!此处不鼓励仅使用代码的答案,因为它们无法深入了解问题是如何解决的。请更新您的答案,以说明您的代码如何解决手头的问题:) 非常感谢,@Joel。我已根据您的建议更新了答案。【参考方案12】:

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

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

    隐私 - 照片库使用说明 -> NSPhotoLibraryUsageDescription

    隐私 - 相机使用说明 -> NSCameraUsageDescription

[

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

谢谢!

【讨论】:

【参考方案13】:

你可以在这里做

var avatarImageView = UIImageView()
var imagePicker = UIImagePickerController()
        
func takePhotoFromGallery() 
    imagePicker.delegate = self
    imagePicker.sourceType = .savedPhotosAlbum
    imagePicker.allowsEditing = true
    
    present(imagePicker, animated: true)


func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
    if let pickedImage = info[.originalImage] as? UIImage 
        avatarImageView.contentMode = .scaleAspectFill
        avatarImageView.image = pickedImage
    
    self.dismiss(animated: true)

希望对你有帮助

【讨论】:

【参考方案14】:

这是一个简单的方法:

但首先您必须在 info.plist 中添加(隐私 - 照片库使用说明),并且您的 viewController 中应该有一个按钮和一个 UIImageView。

然后创建 UIImageView 的插座(在此代码中,插座称为 myImage)和按钮的操作(我在代码中称为操作导入)

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
    


【讨论】:

【参考方案15】:
@IBAction func ImportImage(_ sender: Any)

    let image = UIImagePickerController()
    image.delegate = self

    image.sourceType = UIImagePickerController.SourceType.photoLibrary

    image.allowsEditing = false

    self.present(image, animated: true)
    
        //After it is complete
    




func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    
        myimage.image = image
    
    else
        //
    
    self.dismiss(animated: true, completion: nil)

    do 
        try context.save()
     catch 
        print("Could not save. \(error), \(error.localizedDescription)")
    


在类定义中添加UINavigationControllerDelegateUIImagePickerControllerDelegate委托

【讨论】:

添加cmets,解释你的答案,阅读how to answer。【参考方案16】:

如果您不想使用单独的按钮,这里还有另一种方法。在 imageView 本身上附加了一个手势,点击图像时会弹出一个带有两个选项的警报。您可以选择从图库/照片库中选择或取消警报。

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 中的逻辑。

【讨论】:

【参考方案17】:

单击按钮并打开图片库并在 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)

【讨论】:

【参考方案18】:

试试这个很简单.. 使用 UIImagePickerControllerDelegate

来绘制图片
    @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)
    

【讨论】:

【参考方案19】:

如果你只想选择普通图像,你可以使用下面的代码,检查选择的图像不是全景图像。

let picker = UIImagePickerController()

func photoFromLibrary() 

        self.picker.allowsEditing = true
        self.picker.sourceType = .photoLibrary
        //picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!

        self.present(self.picker, animated: true, completion: nil)



func shootPhoto() 

            if UIImagePickerController.isSourceTypeAvailable(.camera) 
                self.picker.allowsEditing = true
                self.picker.sourceType = UIImagePickerControllerSourceType.camera
                self.picker.cameraCaptureMode = .photo
                self.picker.modalPresentationStyle = .fullScreen
                self.present(self.picker,animated: true,completion: nil)
            



//Image picker delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 

    let str = "\(info["UIImagePickerControllerOriginalImage"]!)"

    let s = str.slice(from: "", to: "")

    if let arr = s?.components(separatedBy: ",")
        if arr.count >= 2 
            if Int(arr[0])! > 11000 
                picker.dismiss(animated:true, completion: nil)
                self.makeToast("Invalid Image!!!")
                return
            
                     
        
    

    if  let image = info[UIImagePickerControllerOriginalImage] as? UIImage
        self.UserImageView.image = image
    
    picker.dismiss(animated:true, completion: nil)



func imagePickerControllerDidCancel(_ picker: UIImagePickerController)

    picker.dismiss(animated: true, completion: nil)

【讨论】:

【参考方案20】:

对于 Swift 3.4.1,此代码有效:

implements                                                             
class AddAdvertisementViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate  

var imagePicker = UIImagePickerController()                                
var file :UIImage!

 //action sheet tap on image

 func tapOnButton()   
    let optionMenu = UIAlertController(title: nil, message: "Add Photo", preferredStyle: .actionSheet)

    let galleryAction = UIAlertAction(title: "Gallery", style: .default, handler:
        (alert: UIAlertAction!) -> Void in
        self.addImageOnTapped()
    )

    let cameraAction = UIAlertAction(title: "Camera", style: .default, handler:
        (alert: UIAlertAction!) -> Void in
        self.openCameraButton()
    )

    let cancleAction = UIAlertAction(title: "Cancel", style: .cancel, handler:
        (alert: UIAlertAction!) -> Void in
        print("Cancel")
    )

    optionMenu.addAction(galleryAction)
    optionMenu.addAction(cameraAction)
    optionMenu.addAction(cancleAction)
    self.present(optionMenu, animated: true, completion: nil)



func openCameraButton()
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
    
        imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    



func addImageOnTapped()
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary)
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    


//picker pick image and store value imageview
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    
            file = image
            imgViewOne.image = image
        imagePicker.dismiss(animated: true, completion: nil);
    

【讨论】:

以上是关于如何允许用户使用 Swift 选择图像?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 中像数组一样访问图像资源

如何从图像文字数组中选择单个图像并将其保存为swift 5中的用户默认值

ios swift将图像裁剪为设备大小

如何在Swift中调整图像大小?

存储对相机胶卷图像的引用 - Swift 4

将项目添加到数组 Swift