我正在用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 Scene-
View Controller - Top Layout Guide - Bottom Layout Guide - View - Image View First Responder Exit
但是,当我启动该应用程序时,仅显示黑屏。我做错了什么?我发现的另一个示例代码是在Objective-C中,这对我没有帮助。
如果只想让用户使用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 } }