【问题标题】:How to print/pass the text of a Button in a tableViewCell to another ViewController in Swift?如何在 Swift 中将 tableViewCell 中的 Button 文本打印/传递到另一个 ViewController?
【发布时间】:2021-05-07 01:52:35
【问题描述】:

我想在单击该特定 tableViewCell 时打印该按钮的文本。还要注意点击也会关闭视图。请帮我解决这个问题

以下是我尝试过的代码:

extension AlertViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return flags.count
    }
    
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let flag = flags[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "FlagTableViewCell") as! FlagTableViewCell
        cell.setUp(flag: flag)
        //clickedFlagName = cell.flagNameLbl.text!
//        print("Clickeeeeeeeeeeddddddd" + "\(clickedFlagName)")
        clickedFlagName = cell.flagNameBtn.title(for: .normal)!
        print("WhennnnClickeeeeeeeeeeddddddd   " + "\(clickedFlagName)")
        cell.flagNameBtn.addTarget(self, action: #selector(self.clickedFlagAction), for: .touchUpInside)
        
        return cell
    }
    
   
    @objc func clickedFlagAction(_ sender: Any?) {
        print("Tapped")
        dismiss(animated: true)
    }
}
 

【问题讨论】:

  • 请勿发布代码图片。

标签: ios swift tableview swift5


【解决方案1】:

使用未附加任何操作但带有 IBOutlet 的按钮设置您的 FlagTableViewCell。我们就叫它flagCellButton吧。

在您的 tableView(_:cellForRowAt:) 方法中,

像您现在所做的那样,将一个单元格出列并将其转换为 FlagTableViewCell 类型。然后在flagCellButton上调用removeTarget(_:action:for:),传入nil作为target和action,.touchUpInside作为控制事件。 (这会清除回收单元格中的所有操作。)

调用 cell.flagCellButton.addTarget(_:action:for:) 以在单元格上从您的视图控制器添加 IBAction。

设置您的 IBAction 以期望发件人是 UIButton 类型。在该 IBAction 中,获取发送者的标题,并将该标题传递给新的视图控制器,然后关闭当前的视图控制器。

编辑:

请注意,如果您将应用设置为要求 iOS >= v 14,则可以使用 UIControl 中的新方法,让您将 UIAction 附加到按钮/控件而不是目标/操作。 UIAction 的优点是它采用闭包而不是选择器,因此您可以提供内联代码,而不必在视图控制器中定义 IBAction 方法。您可以使用类似的方法从按钮中删除旧的 `UIAction 并添加一个新的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多