如果您只是想要處理單元格選擇,則可以使用UICollectionViewDelegate中的handy method來獲取按下單元格的索引路徑。
如果你的目標是使細胞內的自定義按鈕(或者甚至幾個),你可以以任何方式,包括推/呈現新的控制器使用委託模式來獲取用戶的操作將控制器不是過程。將控制器的實例(管理集合視圖的實例)分配給單元的代理成員。
- 定義一個協議,我會打電話給
MyCustomCellDelegate
(將MyCustomCell替換爲更適合您的情況的名稱)。類似於MyCustomCellDelegate: class { func didPressButtonX() }
- 在您的單元格子類中聲明一個可選的委託屬性。
weak var delegate: MyCustomCellDelegate?
- 通過要到按下按鈕(或您的協議定義的任何其它交互)迴應類實現的委託協議。
- 創建/每次出列的單元爲您UICollectionView使用您的委託屬性設置爲視圖控制器管理的集合視圖。
cell.delegate = self
(如果在視圖控制器本身內部完成)。
- 在您的自定義單元格內接收到UI事件後,使用您的委託屬性將操作檢索到控制器(或分配屬性時使用的對象)。喜歡的東西:
delegate?.didPressButtonX()
- 在你的類,它實現
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")
}
}
對不起,我在下面的這個麻煩。你可能寫出一些示例代碼?謝謝。 –
@ArchieGertsman剛剛更新了我的答案,讓我知道是否需要進一步澄清。 –
這更清晰。但是,我根本不使用故事板。如果我以編程方式執行所有操作,此代碼是否仍然有效? –