2017-04-22 34 views
1

我有一個UICollectionViewController一個UICollectionViewCell標題,我添加了一個按鈕即可。我希望點擊按鈕時,可以將新視圖控制器推到當前視圖控制器上。問題是該按鈕無法訪問UICollectionViewController的導航控制器,所以我無法直接將控制器從連接器(例如,連接器)推送到buttn(我知道)。有什麼辦法可以做到這一點?也許有些東西可以被重寫,比如collectionView函數。謝謝!斯威夫特Add按鈕UICollectionViewCell打開新的控制器

回答

1

如果您只是想要處理單元格選擇,則可以使用UICollectionViewDelegate中的handy method來獲取按下單元格的索引路徑。

如果你的目標是使細胞內的自定義按鈕(或者甚至幾個),你可以以任何方式,包括推/呈現新的控制器使用委託模式來獲取用戶的操作將控制器不是過程。將控制器的實例(管理集合視圖的實例)分配給單元的代理成員。

  1. 定義一個協議,我會打電話給MyCustomCellDelegate(將MyCustomCell替換爲更適合您的情況的名稱)。類似於MyCustomCellDelegate: class { func didPressButtonX() }
  2. 在您的單元格子類中聲明一個可選的委託屬性。 weak var delegate: MyCustomCellDelegate?
  3. 通過要到按下按鈕(或您的協議定義的任何其它交互)迴應類實現的委託協議。
  4. 創建/每次出列的單元爲您UICollectionView使用您的委託屬性設置爲視圖控制器管理的集合視圖。 cell.delegate = self(如果在視圖控制器本身內部完成)。
  5. 在您的自定義單元格內接收到UI事件後,使用您的委託屬性將操作檢索到控制器(或分配屬性時使用的對象)。喜歡的東西:delegate?.didPressButtonX()
  6. 在你的類,它實現MyCustomCellDelegate使用的方法來推動新的控制器。

下面我將提供的示例代碼,應該給上提出的解決方案的實施更多的細節:

// In your UICollectionViewCell subclass file 

protocol MyCustomCellDelegate: class { 
    func didPressButtonX() 
    func didPressButtonY() 
} 

MyCustomCell: UICollectionViewCell { 
    weak var delegate: MyCustomCellDelegate? 

    @IBOutlet var buttonX: UIButton! 
    @IBOutlet var buttonY: UIButton! 

    @IBAction func didPressButtonX(sender: Any) { 
     delegate?.didPressButtonX() 
    } 

    @IBAction func didPressButtonY(sender: Any) { 
     delegate?.didPressButtonY() 
    } 
} 

// Now in your UICollectionViewController subclass file 

MyCustomCollectionViewController: UICollectionViewController { 
    // ... 

    override func collectionView(UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier identifier: "YourCellIdentifierGoesHere", for indexPath: indexPath) as! MyCustomCell 
     // In here we assign the delegate member of the cell to make sure once 
     // an UI event occurs the cell will call methods implemented by our controller 
     cell.delegate = self 

     // further cell setup if needed ... 

     return cell 
    } 
} 

// In order for the instance of our controller to be used as cell's delegate 
// we implement the protocol that we defined earlier in the cell file 
extension MyCustomCollectionViewController: MyCustomCellDelegate { 
    func didPressButtonX() { 
     print("X button was pressed") 

     // now lets finally push some new controller 
     let yourNextCoolViewController = UIViewController() 
     self.push(yourNextCoolViewController, animated: true) 

     // OR if you are using segues 
     self.performSegue(withIdentifier: "YourSegueIdentifierGoesHere", sender: self) 
    } 

    func didPressButtonY() { 
     print("Y button was pressed") 
    } 
} 
+0

對不起,我在下面的這個麻煩。你可能寫出一些示例代碼?謝謝。 –

+0

@ArchieGertsman剛剛更新了我的答案,讓我知道是否需要進一步澄清。 –

+0

這更清晰。但是,我根本不使用故事板。如果我以編程方式執行所有操作,此代碼是否仍然有效? –