UIImagePickerController导入图像

时间:2018-07-28 22:47:45

标签: ios swift uikit

我想从库中导入ios中的图像,但是我有错误

  

'viewcontroller'类型的值没有成员'present'

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


    @IBAction func Alert(sender: AnyObject) {

        let nextController = UIImagePickerController()
        self.present(nextController, animated: true, completion: nil)


    }}

1 个答案:

答案 0 :(得分:0)

这是我的剥离后的工作代码。我使用两个选择器-一个用于相机,一个用于库-因为有些奇怪的iOS bug带有色彩。为了避免出现“大规模视图控制器”问题,我倾向于将与UIImagePickerController相关的所有内容移至单独的文件和扩展名中。

class OpenViewController: UIViewController {

    let pickerLibrary = UIImagePickerController()
    override func viewDidLoad() {
        super.viewDidLoad()
        pickerLibrary.delegate = self

    }
}

extension OpenViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

   @objc func showImagePicker() {
        pickerLibrary.allowsEditing = false
        pickerLibrary.sourceType = .photoLibrary
        present(pickerLibrary,
                animated: true,
                completion: nil)
        pickerLibrary.popoverPresentationController?.sourceView = self.view
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: false, completion: nil)
    }
}

虽然present代码看起来正确,但我注意到您没有在代码中发布的几件事。也许是因为您没有发布,但我肯定会检查以下内容:

  • 您是否将ViewController设置为代表?
  • 您是否将ViewController.view设置为源视图? iPhone可能不需要此功能,但iPad绝对有帮助。
  • 您是否包括为UIImagePickerControllerDelegate, UINavigationControllerDelegate工作所需的一切?

现在,正如您的错误所暗示的那样,可能还有其他问题-UIViewController 可以 present另一个视图控制器。在这种情况下,您没有给我们提供重复该错误的方法。换句话说,我假设(1)您看到UIButton上附加了Alert()-顺便说一句,Swift约定为此使用了小写字母-并且(2)您证明了当点击按钮,实际上将执行“ Alert()”。