swift UIViewController用于自定义单元格中的按钮

问题描述 投票:0回答:3

我有一个自定义表格视图单元格,它有一个标签视图。我添加了tapGesture以在单击该视图时调用函数。目前我的自定义视图单元格在它自己的swift文件中。我添加了以下代码,以便在点击该标签时启用“共享扩展”。

  CustomCellView.swift

  10 myLabel.isUserInteractionEnabled = true
  11 let tap = UITapGestureRecognizer(target: self, action: #selector(tapLabelGesture))
  12 myLabel.addGestureRecognizer(tap)

  13 func tapLabelGesture() {
  14   print("Clicked on Label ")
       let url="www.google.com"
  15   let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)

  16   activityVC.popoverPresentationController?.sourceView = self.view
  17   self.present(activityVC, animated: true, completion: nil)
  18 }

我在第16行获得了self.view的编译错误,而在self.present()中获得了17。问题是如何为弹出窗口提供视图?

这个代码我用于另一个视图(没有表视图或单元格)作为测试,它工作正常。所以我正在尝试为tableview / cell做同样的技术。我该如何解决这个问题?任何帮助表示赞赏。

swift uiviewcontroller
3个回答
1
投票

对于第16行:

你得到一个错误,说你的班级CustomCellView没有成员view,因为你的类是UITableViewCell的子类而不是UIViewController因为UIViewController有这个属性而你的CustomCellViewcontentView

对于第17行:

同上,你的类不是UIViewController的子类,这就是为什么你不能使用self.present

解:

而不是使用UITapGestureRecognizer你可以使用UIButton,你可以放在UILabel和你的UIViewController类添加button.tagbutton.addTarget在你的cellForRowAt方法。

然后,您可以在按钮方法中添加代码并显示UIActivityViewController

希望这会有所帮助。


0
投票

正如@DharmeshKheni所提到的,你不能像UITableViewCell那样使用UIViewController的子类。它不提供view属性和present方法。

回答你的问题,你可以在CustomCellView中存储一个闭包:

var onLabelTappedCallback: (() -> Void)?

在你的选择器中调用它:

@objc private func tapLabelGesture() {
    onLabelTappedCallback?()
}

最后在cellForRowAt方法中实现:

cell.onLabelTappedCallback = {
    print("Label tapped")
    //Present additional vc
}

此解决方案也适用于UIButton


0
投票

我从这个帖子中获得了更多关于SO的想法,how to recognize label click on custom UITableViewCell - Swift 3通过扩展,我能够解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.