如何在UIViewController的自定义函数中从UITableViewCell访问UIImageView

时间:2019-04-02 09:57:43

标签: ios swift

当相机关闭时,我尝试将图像(位于UIViewController中)分配给UIImageView(位于UITableViewCell中)。 问题是我无法在需要的那个函数中从Cell访问UIViewController。 我需要在哪里设置UIImageView以便能够从UIViewController的函数中访问它?

我已经尝试使用委托方法将我的UIImageView传递给UIViewController,然后再调用此委托方法并分配图像。但是由于某些原因无法正常工作。

这是我的UITableViewCell代码:

/**
 * @ORM\PrePersist
 */
public function _prePersist()
{
  dump($this);die;
}

这是我来自UIViewController的代码:

protocol DefectAndDamageCellDelegate {
    func receiveImageViewFromCell(imageView: UIImageView)
}

class DefectAndDamageCheckCell: UITableViewCell {

    // Interface Links
    @IBOutlet weak var defectImageView: UIImageView!

    // Properties
    var delegate: DefectAndDamageCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }

    func configCell(){
        delegate?.receiveImageViewFromCell(imageView: defectImageView)
    }
}

这是我的问题的GitHub小示例。要访问相机,您需要按住单元格上的。 https://github.com/tygruletz/sendDataFromCellToController/

谢谢!

1 个答案:

答案 0 :(得分:3)

重点是要有一些数据源数组

var images = [UIImage]()

声明您的表格视图有多少个单元格

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return images.count
}

然后使用此数据源,您可以说类似的话,如果这是IndexPath的单元格,请设置此图像。为此,您可以轻松访问UIImageView中特定单元格的cellForRowAt,不需要委托协议

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: Constants.defectAndDamageCell, for: indexPath) as! DefectAndDamageCheckCell
    cell.defectImageView.image = images[indexPath.row]
    return cell
}

因此,当UIImagePickerController拾取图像时,请更改表格视图的数据源(附加此新图像),然后将新行插入表格视图

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
    imagePicker.dismiss(animated: true, completion: nil)
    guard let selectedImage = info[.originalImage] as? UIImage else {
        print("Image not found!")
        return
    }

    images.append(selectedImage)
    tableView.insertRows(at: [IndexPath(row: images.count - 1, section: 0)], with: .automatic)
}