2016-11-30 37 views
1

我在嘗試使用配方上傳功能來構建食譜應用程序。在PostController中,所有烹飪步驟將有一個桌面視圖,每個烹飪步驟都在桌面視圖單元中。在單元格中將會有一個文本域的描述和一個UIImageView用於圖片上傳(從pickerController中選擇的圖片將在這個UIImageView中顯示以供以後上傳)。我正在嘗試執行 imageViewInCell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageUpload))) 以調用生成UIImagePickerController的handleImageUpload()函數。但是通過這樣做,我遇到了兩個問題。在每個tableview單元格中使用UIImagePickerController

  1. 我不能在UITapGestureRecognizer由選擇器獲得的小區的index.row值,與列的索引我不能選擇的圖像分配返回到信元的的UIImageView。
  2. 即使我在handleImageUpload中獲得了index.row,我仍然需要下面的函數來分配選定的圖像。這個函數如何接受我的參數並找到相應的imageViewInCell?

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
        if let selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage { 
         imageViewInCell.image = selectedImage 
        } 
        dismiss(animated: true, completion: nil) 
    } 
    
+1

爲什麼使用輕擊手勢而不是didSelectRowAtIndexPath? –

+0

我爲imageView添加了UITapGesture,因爲此操作僅僅與圖片相關。使用didSelectRowAtIndexPath可能不是選擇,因爲單元格中還有一個文本字段。 –

+0

最後,我每次調用'handleImageUpload()'時都保存了全局變量'selectedIndex'(由didFinishPickingMediaWithInfo'使用)和'cell.imageViewInCell.tag'(由'handleImageUpload()'使用)的索引,它賦值'cell.imageViewInCell.tag'的'selectedIndex'。在'didFinishPickingMediaWithInfo'中,它使用全局變量來查找相應的單元格。 –

回答

1

可以設置indexPath.row在你的cellForRowAtIndexPath的imageview的像下面

cell.yourImageView.tag = indexPath.row 

標籤,然後你可以用下面

let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0) 
let cell = tableView.cellForRowAtIndexPath(indexPath) as! yourcellClass! 
cell.yourImgeView.image = selectedImage 
+0

這個想法有幫助。問題現在已經解決了,謝謝! –

+0

歡迎開心編碼.... –

0
得到這個indepath backagain

我假設你只想在imageView上調用thehandleImageUpload()而不是整個單元,因此您使用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) 
} 
+0

使用手勢方法,您只能傳遞GestureRecognizer對象而不是其他任何東西。 –

+0

好的,讓我編輯一下。 –

+0

編輯答案。 –

相關問題