【问题标题】:how to get share button to work in tableview cell swift?如何让共享按钮在 tableview 单元格中快速工作?
【发布时间】:2021-12-26 13:53:57
【问题描述】:

我是 swift 新手,我正在使用 tableviews 创建提要。我有一个自定义表格视图单元格,它有一个按钮,并且我包含了一个 IBAction 函数,用于在单元格上点击按钮时使用。

@IBAction func didTapShareBtn(_ sender: Any) {
    // display share screen with url
}
  1. 如何获取此操作的特定数据(网址)?
  2. 如何创建共享屏幕 - 当我尝试实现此功能时,我收到一条错误消息 - “'FeedListTableViewCell' 类型的值没有成员 'present'”

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您不想尝试从您的单元内部展示共享屏幕。

    推荐的方法是使用closure,这样您的单元格就可以告诉控制器该按钮已被点击,控制器将处理该操作。

    快速示例 - 假设您有一个带有标签和按钮的单元格:

    class FeedListTableViewCell: UITableViewCell {
        
        var btnTapClosure: ((FeedListTableViewCell)->())?
    
        @IBOutlet var theLabel: UILabel!
        
        @IBAction func didTapShareButton(_ sender: Any) {
            // tell the controller the button was tapped
            btnTapClosure?(self)
        }
        
    }
    

    当您的表格视图控制器使单元格出列时,我们设置标签文本并且我们设置闭包:

    class FeedTableViewController: UITableViewController {
        
        var myData: [String] = [
            "https://apple.com",
            "https://google.com",
            "https://stackoverflow.com",
        ]
        
        override func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return myData.count
        }
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedListTableViewCell
            cell.theLabel.text = myData[indexPath.row]
            
            // set the closure
            cell.btnTapClosure = { [weak self] cell in
                // safely unwrap weak self and optional indexPath
                guard let self = self,
                      let indexPath = tableView.indexPath(for: cell)
                else { return }
                
                // get the url from our data source
                let urlString = self.myData[indexPath.row]
                guard let url = URL(string: urlString) else {
                    // could not get a valid URL from the string
                    return
                }
                
                // present the share screen
                let objectsToShare = [url]
                let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
                self.present(activityVC, animated: true, completion: nil)
    
            }
            
            return cell
        }
        
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2019-09-02
      • 2013-05-10
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多