我正在尝试使用配方上传功能构建配方应用程序。在PostController中,将有一个所有烹饪步骤的表格视图,每个步骤都在一个tableview单元格中。在单元格中将有一个描述的文本字段和用于图片上传的UIImageView(从pickerController中选择的图片将显示在此UIImageView中以供稍后上传)。我正在尝试使用imageViewInCell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageUpload)))
来调用生成UIImagePickerController的handleImageUpload()
函数。但通过这样做,我遇到了两个问题。
index.row
中的选择器获取单元格的UITapGestureRecognizer
值,而索引我无法将所选图像分配回单元格的UIImageView。func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageViewInCell.image = selectedImage
}
dismiss(animated: true, completion: nil)
}
您可以将indexPath.row设置为cellForRowAtIndexPath中imageview的标记,如下面所示
cell.yourImageView.tag = indexPath.row
然后你可以使用下面的方法获得这个unpath
let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath) as! yourcellClass!
cell.yourImgeView.image = selectedImage
我假设你只想在thehandleImageUpload()
而不是整个单元格上调用imageView
,因此你使用tapGesture。
现在回答您的问题,将标签分配给您的imageView,如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
//cell configuration
cell.imageView.tag = indexPath.row
return cell
}
您可以将选定的图像分配给选定的单元格,如下所示:
现在你的handleImageUpload()
是:
func handleImageUpload(_ sender: UITapGestureRecognizer){
selectedIndexPath = sender.tag
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let cell = self.tableView.cellForRowAtIndexPath(selectedIndexPath) as UITableViewCell
cell.imageViewInCell.image = selectedImage
}
dismiss(animated: true, completion: nil)
}
我参加派对的时间已经很晚了,但下面的代码应该可行。
我有UITableViewCell做处理图像的工作。使它成为一个UIPickerControllerDelegate并让它保持一个闭包以在必要时呈现选择器(因为它不能呈现某些东西,因为它不是视图控制器)。
就像是:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let photoCell = tableView.dequeueReusableCell(withIdentifier: "PhotosTableViewCell", for: indexPath) as! PhotosTableViewCell
photoCell.takePicture = {[weak self] in
let imagePicker = UIImagePickerController()
imagePicker.delegate = photoCell
imagePicker.sourceType = .camera
self?.present(imagePicker, animated: true, completion: nil)
}
让你的UITableviewCell实现:
var takePicture: (() -> Void)?
关闭。然后从按钮或其他东西中调用它以使其触发。使用:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
处理图像。