我在UICollectionViewCell
上有一个UICollectionViewController
标题,我已添加了一个按钮。我希望按钮在单击时按下当前按钮上的新视图控制器。问题是该按钮无法访问UICollectionViewController
的导航控制器,所以我无法直接将控制器从连接器推到按钮(即我知道)。有没有办法实现这个目标?也许可以覆盖某些东西,例如collectionView
函数。谢谢!
答案 0 :(得分:1)
如果您只想处理单元格选择,则可以在UICollectionViewDelegate中使用handy method来获取压缩单元格的索引路径。
如果你的目标是在单元格内部(或者甚至是几个)中有一个自定义按钮,你可以使用委托模式来检索控制器的用户操作,而不是以任何方式处理,包括推送/呈现新控制器。将控制器的实例(管理集合视图的实例)分配给单元的委托成员。
MyCustomCellDelegate
的协议(用你的案例更恰当的名称替换MyCustomCell)。像MyCustomCellDelegate: class { func didPressButtonX() }
weak var delegate: MyCustomCellDelegate?
cell.delegate = self
(如果在视图控制器内完成)。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")
}
}