2017-10-07 50 views
0

我已經把一個uicollectionview放入了一個uitableview。在選擇表視圖單元格內的collectionview單元格後,我遇到了另一個viewcontroller的麻煩。從uicollectionview中查看是在桌面視圖內

// if the user selects a cell, navigate to the viewcontroller 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    // we check did cell exists or did we pressed a cell 
    if let cell = sender as? UICollectionViewCell { 

     let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell") as! TestingTableView 

     // define index to later on pass exact guest user related info 
     let index = cell2.collectionView?.indexPath(for: cell)!.row 

     print(index as Any) 

     // if segue is guest... 
     if segue.identifier == "guest" { 

      // call guestvc to access guest var 
      let guestvc = segue.destination as! GuestCommunityViewVC 

      // assign guest user inf to guest var 
      guestvc.guest = communities[index!] as! NSDictionary 


     } 

    } 

} 

} 

我在該行收到一個錯誤:

let index = cell2.collectionView?.indexPath(for: cell)!.row 

,因爲跟它的價值爲零。有沒有人知道一個更好的方法來做到這一點?

+0

在上面的錯誤提示行中,您將出現一個單元格並將其轉換爲TestingTableView對象。你的意思是把這個當作一個TableViewCell嗎? – bjd23

+0

@ bjd23我的集合視圖插座是在表視圖單元類中聲明的,因爲它嵌套在表視圖中。這是我可以訪問collectionview的索引路徑的唯一方法。但是,如果它返回nil,我認爲它甚至不會獲得collectionview的indexpath。我一直在爲此奮鬥一段時間。有什麼建議麼? – ILoveToCode22

+0

爲什麼不使用委託,所以當按下UICollectionViewCell時,它會將此內容發送給UITableView所在的ViewController? – Jay

回答

1

下面是如何使用委託的示例:

1)的一類聲明之外創建一個協議:

protocol customProtocolName:class { 
     func pushToNewView(withData:[DataType]) 
} 

注:爲了防止一個參考週期使用類

2)創建保持該參考UICollectionView所述的UITableViewCell內部的代表:

class customUITableViewCell { 
     weak var delegate:customProtocolName? = nil 
} 

3),它保存參考的UITableView的UIViewController的內部,確保你補充協議,除了類的聲明,並添加我們創建,以確保協議規範滿意的功能:

class customViewController: customProtocolName { 
    func pushToNewView(withData:[DataType]) { 
     //inside here is where you will write the code to trigger the segue to the desired new UIViewController 
     //You can take this new data and store it in this ViewController and then during the segue pass it along 
    } 
} 

4)的的UITableViewDelegate功能,「cellForRowAt」,設置委託customUITableViewCell內部自我:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customUITableViewCell 
     cell.delegate = self 
    return cell 
} 

5)customUITableViewCell,其中UICollectionView委託函數處理內部「didSelectItemAt」委託功能,觸發協議功能有像這樣:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    delegate?.pushToNewView(withData:[DataType]) 
} 

這是一個非常簡單的例子,如果你想傳遞一個IndexPath,那麼你可以修改函數來進行。你也可以傳回任何你想要的東西,它不受限制。

+0

但我如何將一個在tableViewCell類中的數組與segue轉移到下一個viewController –

+1

我修改了我的答案以顯示如何使用委託來傳遞數據,然後在segue委託函數期間,您可以將信息傳遞給下一個viewController。嘗試忽略命名約定,這是一個非常簡單的例子,您需要爲您修改項目。另外「DataType」是可以互換的自定義數據對象類型,如果您創建了一個,那麼您將使用該類型。 – Jay