2015-08-15 34 views
0

我已經添加了一個UILongPressGestureRecognizer到我的UICollectionViewCell並創建了一個segue,所以通過長按cell用戶跳到ViewController發送細胞數據到destinationViewController與prepareForSegue

我已經有一個普通的使用didSelect方法顯示細胞的細節,但次要長按手勢segue使用戶到一個操作屏幕刪除細胞。

不幸的是使用prepareForSegue何時發送單元格數據到destinationViewController因爲我用手勢識別器,當創建我自己的選擇,我不能使用標準let indexPaths = self.collectionView.indexPathForSelectedRow()方法。

那麼如何使用gestureRecognizer將單元格數據發送到destinationViewControllerprepareForSegue

if segue.identifier == "cellAction" { 
    let vc = segue.destinationViewController as! CellActionViewController 

    //This will cause an 'array index out of range error 
    let indexPaths = self.collectionView.indexPathsForSelectedItems() 
    let indexPath = indexPaths[0] as! NSIndexPath 

    //Here is how I would send the cell data 
    let selectedCell = Items[indexPath.row] 

    vc.selectedItem = selectedCell 
} 

回答

1

所以,你需要訪問被按下特定的細胞,並利用這些信息從prepareForSegue(_:sender:)內獲得其索引路徑。

首先要注意的是prepareForSegue方法中的sender參數。我認爲你從你的手勢處理函數調用performSegueWithIdentifier(_:sender:)。注意這也有一個sender參數,它是傳遞給prepareForSegue的同一個對象。你可以用它來傳遞你的單元實例。

第二件要注意的是,UIGestureRecognizer有一個view屬性,這應該很可能是單元格本身。具備了這些知識,您可以在按壓的單元實例傳遞給prepareForSegue

func handleLongPress(longPress: UILongPressGestureRecognizer) { 
    if longPress.state == .Ended { 
     performSegueWithIdentifier("cellAction", sender: longPress.view) 
    } 
} 

現在,內prepareForSegue你可以投sender到您的類,並且使用UICollectionView小號indexPathForCell(_:)方法獲得它的索引路徑:

override prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "cellAction" { 
     let vc = segue.destinationViewController as! CellActionViewController 
     if let cell = sender as? MyCell { 
      let indexPath = collectionView.indexPathForCell(cell) 
      let selectedItem = items[indexPath.row] 
      vc.selectedItem = selectedItem 
     } else { 
      fatalError("Invalid sender, was expecting instance of MyCell.) 
     } 
    } 
} 
+0

非常感謝你的回覆,你對我如何使用這個姿勢是正確的。不幸的是,我仍然是一個初學者,並且不能確定你在將單元格發送給單元類時的意思。我已經創建了一個自定義的UICollectionViewCell類。 – RileyDev

+0

在'prepareForSegue'中,'sender'的類型是'AnyObject?',因爲它可以是任何類或'nil'的對象。您需要使用'as?'運算符的可選綁定將其下傳到'MyCell'(或者您的任何單元子類被調用)。這是最後一個代碼塊中的這一行:'if let cell = sender as? MyCell'。您需要將它轉換爲您的單元類,以便編譯器知道您將'MyCell'實例傳遞給'indexPathForCell(_ :)',而不是'AnyObject?',這會導致編譯器錯誤。 – Stuart

+1

好吧我明白,謝謝你的幫助,我真的很感激它。我喜歡瞭解代碼而不是一味地複製粘貼和回答(Y) – RileyDev