【问题标题】:Show view at taped button inside UICollectionView Cell在 UICollectionView 单元格内的录音按钮上显示视图
【发布时间】:2020-05-15 21:51:58
【问题描述】:

我正在开发一个包含 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
}

但这没有用,我该怎么做才能得到它?

【问题讨论】:

  • 澄清一下,myView 包含在您的UICollectionViewCell 中,并且在选择时您希望视图显示在所选单元格的后面?如果您也滚动,myView 是否应该留在您的 UICollectionViewCell 后面?还是只是选择?
  • 不,它不是 UICollectionViewCell,我希望它只出现在选择中,并在滚动时隐藏。

标签: ios swift uicollectionview uibutton uicollectionviewcell


【解决方案1】:

实际上,您可以在 UICollectionViewCell 中使用协议。它比使用 forge 更健康。

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
}

【讨论】:

  • 那只是调用函数,这不是我的问题,我的问题是如何在点击按钮的位置显示一个uiview?
  • 好的,我将编辑我的帖子以添加显示视图,但我必须知道您的视图必须显示在哪里?在单元格内部或视图控制器内部但在单元格附近?你能提供更多信息吗?
  • 它出现在 viewcontroller 内点击单元格上方,点击按钮下方。
【解决方案2】:
 @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
        }
    }

【讨论】:

    猜你喜欢
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多