2015-05-19 52 views
9

我面臨的問題是將我從畫廊中選擇的圖片放入UIImageView(imageChosen)。將從畫廊拍攝的圖像設置爲UIImageView

的代碼運行正常,沒有任何錯誤,但我選擇的圖片沒有被設置爲「imageChosen」

這裏是我的代碼

class postChoices: UIViewController { 

    @IBOutlet weak var imageChosen: UIImageView! 

    @IBAction func gallery(sender: AnyObject) { 

     var image = UIImagePickerController() 
     //image.delegate = self 
     image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary 
     image.allowsEditing = false 

     self.presentViewController(image, animated: true, completion: nil) 

    } 
    override func viewDidLoad() { 
     super.viewDidLoad() 

      // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image2: UIImageView!, editingInfo: NSDictionary!) { 
     // let selectedImage : UIImageView = image 
     imageChosen.image = image2.image 

    } 


} 
+0

@adnan沒有工作,我在同一視圖添加imageChosen,self.view –

+0

@adnan好吧,我現在檢查 –

+0

@adnan我在這裏看到這個代碼http://www.theappguruz.com/博客/ user-interaction-camera-using-uiimagepickercontroller-swift /,所有我想要的,所以把圖片放在imageView中,不用創建按鈕,謝謝 –

回答

4
//Complete solution with delegates and image handling  

    import UIKit 

     class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { 

      @IBOutlet weak var myImageView: UIImageView! 
      let picker = UIImagePickerController() 

      @IBAction func gallery(sender: AnyObject) { 

       if UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary) != nil { 
        picker.allowsEditing = false 
        picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary 
        presentViewController(picker, animated: true, completion: nil) 
       } else { 
        noCamera() 
       } 

      } 
      func noCamera(){ 
       let alertVC = UIAlertController(title: "No Camera", message: "Sorry, Gallery is not accessible.", preferredStyle: .Alert) 
       let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil) 
       alertVC.addAction(okAction) 
       presentViewController(alertVC, animated: true, completion: nil) 
      } 

      override func viewDidLoad() { 
       super.viewDidLoad() 
       // Do any additional setup after loading the view, typically from a nib. 
       picker.delegate = self //the required delegate to get a photo back to the app. 
      } 

      //MARK: - Delegates 
      //What to do when the picker returns with a photo 
      func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { 
       var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2 
       myImageView.contentMode = .ScaleAspectFit //3 
       myImageView.image = chosenImage //4 
       dismissViewControllerAnimated(true, completion: nil) //5 
      } 
      //What to do if the image picker cancels. 
      func imagePickerControllerDidCancel(picker: UIImagePickerController) { 
       dismissViewControllerAnimated(true, completion: nil) 
      } 
     } 

Demo Project

+0

使用imageChosen而不是myImageView。只要檢查邏輯,變量名稱並不重要 –

+0

非常感謝,它的工作現在 –

+0

你知道嗎?我從圖庫中選擇了一張圖片後,如何改變爲另一種視圖,我的意思是,有沒有辦法做到這一點,也許在segue或不同的功能 –

2

幾個問題。

如果您查看文檔,方法imagePickerController:didFinishPickingImage:editingInfo:已在iOS 3.0中棄用。

這是一個公平的賭注,它甚至沒有被稱爲。 (您必須設置您的視圖控制器註釋掉委託行,因此圖像拾取不會打電話給你的委託方法。

在你imagePickerController:didFinishPickingImage:editingInfo:方法你必須定義爲一個UIImageView圖像2,它不是,它是一個UIImage。

您應該取消註釋行image.delegate = self

應實現方法imagePickerController:didFinishPickingMediaWithInfo:而不是imagePickerController:didFinishPickingImage:editingInfo:

你可能還需要添加UIImagePickerControllerDelegate到definitio編譯器知道你的視圖控制器符合UIImagePickerControllerDelegate協議。

+0

當我拿出行中的評論image.delegate =自我,錯誤顯示,說不能將類型'PostChoice'的值分配給'協議

+0

好的,然後您需要將UIImagePickerControllerDelegate添加到您的類中,如:class myVC:UIViewController,UIImagePickerControllerDelegate。這告訴編譯器你的類符合'UIImagePickerControllerDelegate'協議。 –

2
- (void) makeUIImagePickerControllerForCamera:(BOOL)camera { 

     UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
     picker.delegate = self; 
     picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; 

     [picker setMediaTypes:[NSArray arrayWithObjects:(NSString *) kUTTypeImage, nil]]; 

     [self presentModalViewController: picker animated: YES]; 
    } 

    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
     // Dismiss the picker 
     [[picker parentViewController] dismissModalViewControllerAnimated:YES]; 

    // Get the image from the result 
    UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"]; 

    myUIImage.image = image; 
} 
0

此代碼幫助我迅速的3.0

internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { 
     billImageView.contentMode = .scaleAspectFill 
     billImageView.image = pickedImage 
    } 
    self.dismiss(animated: true, completion: nil) 
} 

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 
    self.dismiss(animated: true, completion: nil) 
} 
0

在雨燕3.0 在此代碼,你必須選擇這兩個選項的攝像頭和GALLARY

import UIKit 
import Foundation 
import AVFoundation 
class HostVC: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{  
@IBOutlet weak var imgHostProfile:UIImageView! 
    let captureSession = AVCaptureSession() 
    let stillImageOutput = AVCaptureStillImageOutput() 
    var previewLayer : AVCaptureVideoPreviewLayer? 
    var captureDevice : AVCaptureDevice? 

@IBAction func btnChangeprofileTapped(_ sender: UIButton) 
    { 


     DispatchQueue.main.async 
      { 
       let alert = UIAlertController(title: "Alert", message: "Choose profile picture from Camera or Gallery", preferredStyle: UIAlertControllerStyle.alert) 
       alert.addAction(UIAlertAction(title: "Take a photo", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in 
        DispatchQueue.main.async 
         { 
          if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == AVAuthorizationStatus.authorized { 
           self.Cemara() 
          } else { 
           AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in 
            if granted == true { 
             self.Cemara() 
            } else { 
             self.showalert(strMessage: Validation.kCameraAccess) 
            } 
           }) 
          } 

        } 
       })) 
       alert.addAction(UIAlertAction(title: "Choose from Library", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in 
        DispatchQueue.main.async 
         { 
          let imagepicker = UIImagePickerController() 
          imagepicker.delegate = self 
          imagepicker.sourceType = .photoLibrary 

          self.present(imagepicker, animated: true, completion: nil) 
        } 
       })) 

       alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in})) 

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

     } 


    } 

    func Cemara() 
    { 
     DispatchQueue.main.async { 
      if UIImagePickerController.availableCaptureModes(for: .rear) != nil 
      { 
       let imagePicker = UIImagePickerController() 
       imagePicker.delegate = self 
       imagePicker.sourceType = .camera 
       self.present(imagePicker, animated: true, completion: nil) 
      } 
      else 
      { 
       self.noCamera() 
      } 
     } 
    } 

    //====================================================================== 
    //     MARK: - Camera Code 
    //====================================================================== 

    func noCamera() 
    { 
     captureSession.sessionPreset = AVCaptureSessionPresetHigh 
     if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] 
     { 
      for device in devices 
      { 
       if (device.hasMediaType(AVMediaTypeVideo)) 
       { 
        if(device.position == AVCaptureDevicePosition.front) 
        { 
         captureDevice = device 
         if captureDevice != nil 
         { 
          print("Capture device found") 
          beginSession() 
         } 
        } 
       } 
      } 
     } 
    } 

    //====================================================================== 
    //     MARK: - Camera Capture Start Session Code Here 
    //====================================================================== 

    func beginSession() 
    { 
     do 
     { 
      try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice)) 
      stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG] 
      if captureSession.canAddOutput(stillImageOutput) 
      { 
       captureSession.addOutput(stillImageOutput) 
      } 
     } 
     catch 
     { 
      print("error: \(error.localizedDescription)") 
     } 
     guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else 
     { 
      print("no preview layer") 
      return 
     } 
     self.view.layer.addSublayer(previewLayer) 
     previewLayer.frame = self.view.layer.frame 
     captureSession.startRunning() 
     self.view.addSubview(imgHostProfile) 


    } 

    //====================================================================== 
    //     MARK: - Gallary Code 
    //====================================================================== 

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
    { 
     if let imagedata = info[UIImagePickerControllerOriginalImage] as? UIImage 
     { 
      self.imgHostProfile.image = imagedata 
      print(imagedata) 


     } 

     dismiss(animated: true, completion: nil) 
    } 
相關問題