我面临的问题是将我从图库中选择的图片放入UIImageView
(imageChosen)。
代码运行正常,没有任何错误,但我选择的图片未设置为“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 :(得分: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)
}
}
答案 1 :(得分:2)
有几个问题。
如果您查看文档,则在iOS 3.0 中不推荐使用方法imagePickerController:didFinishPickingImage:editingInfo:
。
这是一个公平的赌注,甚至没有被召唤。 (你有一行设置你的视图控制器作为委托被注释掉,所以图像选择器不会调用你的委托方法。
在imagePickerController:didFinishPickingImage:editingInfo:
方法中,您将image2定义为UIImageView。它不是,它是一个UIImage。
您应取消对image.delegate = self
行的评论。
您应该实施方法imagePickerController:didFinishPickingMediaWithInfo:
而不是imagePickerController:didFinishPickingImage:editingInfo:
。
您可能还需要将UIImagePickerControllerDelegate
添加到视图控制器类的定义中,以便编译器知道您的视图控制器符合UIImagePickerControllerDelegate
协议。
答案 2 :(得分: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;
}
答案 3 :(得分:0)
此代码帮助我使用swift 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)
}
答案 4 :(得分:0)
在Swift 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)
}