如何将用户在应用中拍摄的图像保存到UIImage数组中?迅捷4

时间:2018-08-14 17:17:08

标签: ios arrays iphone swift datamodel

我有一个简单的应用程序,用户点击一个按钮即可打开相机,然后他拍摄照片,我希望将该照片附加到UIImages对象数组中。我已经制作了一个不确定的版本。贝娄是我写的代码:

mainPictureVC:

import UIKit
import RealmSwift

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    // var realm: Realm!
    var photoArray = [PhotoArray]()

    @IBOutlet weak var imageView: UIImageView!

    let imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // realm = try! Realm()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let userPickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

//            let imageToUse = PhotoArray()

//            let data = UIImagePNGRepresentation(userPickedImage) //here convert to data

            PhotoArray().photosArray.append(userPickedImage)  //append converted data in array

            imageView.image = userPickedImage
        }
//        print(PhotoArray().photosArray.count)
        imagePicker.dismiss(animated: true, completion: nil)
    }

    @IBAction func cameraButtonPressed(_ sender: UIButton) {
        present(imagePicker, animated: true, completion: nil)
    }

}

我试图通过在tableView控制器上显示来证明我正在保存图像,但是它不起作用。 (我没有收到错误,但他们只是没有出现) TableViewController:

    import UIKit

class TableViewController: UITableViewController {

        //TableView datasource methods

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//            cell.textLabel?.text = categoryArray[indexPath.row].name
//            cell.imageView.image = [UIImage, imageNamed: PhotoArray().photosArray.name];
            cell.imageView?.image = PhotoArray().photosArray as? UIImage
            return cell
        }

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let numberOfRowsInSection = PhotoArray().photosArray
            return numberOfRowsInSection.count 
        }


    }

PhotoArray数据模型:

import Foundation
import UIKit

class PhotoArray: ViewController {
//   var photosArray: [Data] = []
    var photosArray: [UIImage] = []
//    var photosArray: [UIImage] = [UIImage(named: "")!]
}

1 个答案:

答案 0 :(得分:0)

将您的PhotoArray类更改为Singleton。

class PhotoArray {
  static let sharedInstance = PhotoArray()
  var photosArray: [UIImage] = []
}

将所有PhotoArray()都替换为PhotoArray.sharedInstance控制器并运行代码。

希望它可以帮助您解决问题。