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

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

但当我启动应用程序时,只显示黑屏.我做错了什么? 我在Objective-C找到了另外sample code个,这对我没什么帮助.

推荐答案

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

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
    }
}

Ios相关问答推荐

在SwiftUI中插入绘制重复形状

如果没有等待,SWIFT Async让任务抛出取消异常

如何使用Swift以编程方式更改SVG文件中某些元素的 colored颜色

SwiftUI-工作表不显示导航标题

使用异步重载实现Swift协议一致性

更改初始控制器无效

react 本机 |错误:无法解析 node_modules/react-native/index.js 中的模块

将 URLCache 子类与 URLSession 一起使用

在 SwiftUI 中放置全局 NavigationPath 的位置

如何根据条件快速将返回类型设为 LinearGradient 或 AngularGradient?

帧过渡动画有条件地工作

SwiftUI 选项卡式视图防止滑动到下一个选项卡

迁移到 UIKit 生命周期的应用程序不会调用 SceneDelegate

快速禁用 UITextfield 的用户输入

在 Swift 中按下返回键时在文本字段之间切换

如何在 OS X 或 iOS(不使用格式塔)中确定运行时的操作系统版本?

iOS 7 半透明模态视图控制器

无效的 iPhone 应用程序二进制文件

正确使用 Alamofire 的 URLRequestConvertible

文件是为存档而构建的,它不是被链接的体系 struct (i386)