![](/img/trans.png)
[英]How do I send data from a button click in a uicollectionview inside of a popover to a table cell in a main view controller?
[英]Show view at taped button inside UICollectionView Cell
我正在开发一个包含 collectionview 的 iOS 应用程序,在这个 collectionview 中我有一个按钮,如下所示:
ViewController
-UICollectionView(myColl)
--UICollectionViewCell
---UIButton (myButton)
-UIView (myView)
我想要做的是当我点击它时在myButton
下显示myView
,我尝试的是:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell",
for: indexPath) as! TestCell
cell.myButton.addTarget(self, action: #selector(self.showEditView), for: .touchUpInside)
}
并在showEditView()
@objc func showEditView(sender:UIButton!) {
let position: CGPoint = sender.convert(CGPoint.zero, to: self.myColl)
myView.center = position
}
但这不起作用,我该怎么做才能得到它?
@objc func showEditView(sender:UIButton!) {
let position: CGPoint = sender.convert(CGPoint.zero, to: self.collectionview)
let indexPath = self.collectionview.indexPathForItem(at: position)
if indexPath != nil {
myView.center = position
//if your view is hidden
myView.isHidden = false
}
}
实际上,您可以在 UICollectionViewCell 中使用协议。 它比使用伪造使用更健康。
protocol YourProtocolDelegate {
func showEditView()
}
class YourCVCell: UICollectionViewCell {
var delegate: YourProtocolDelegate!
var button = UIButton()
override init(frame: CGRect) {
button.addTapGestureRecognizer {
self.delegate.showEditView()
}
}
}
当然,您必须从您的协议继承到您的 ViewController 类
class YourViewController: UIViewController, YourProtocolDelegate {
}
之后,您可以将单元格的协议引用到您的视图控制器。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell",
for: indexPath) as! TestCell
cell.delegate = self
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.