【问题标题】:Swift: Table View Cell perform segue to two different destinationsSwift:Table View Cell 执行 segue 到两个不同的目的地
【发布时间】:2018-08-05 11:59:22
【问题描述】:

我的问题: 我想在表格视图单元格中对两个不同的目的地执行 segue。一种是通过单击由 didSelectRowAt 处理的单元格来定向目的地“A”,另一种是通过单击单元格内的按钮来定向到目的地“B”,例如 labelName。

对于destination "B",我尝试使用(btn.addTarget),但是它不能添加参数,所以destinatin view controller 不知道点击的是哪个单元格。

有什么建议吗?

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

您可以使用此方法在 btnClick 函数中获取所选 TableviewCell 的 indexPath。

let index = self.tableview.indexPathForSelectedRow

现在通过这样做,您可以解决您提到的这个问题。

目标视图控制器不知道点击了哪个单元格

【讨论】:

    【解决方案2】:

    您可以使用 button.tag 并将每个按钮的标签分配给您的 indexpath.row

    button.tag = indexPath.row
    button.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchUpInside)
    
    func btnClick(sender:UIButton) {
        let buttonRow = sender.tag
    }
    

    对于 Swift 4:

      button.addTarget(self, action: #selector(händlerButtonTapped), for: .touchUpInside)
    
        @objc func händlerButtonTapped(sender:UIButton) {
           let buttonRow = sender.tag
        }
    

    【讨论】:

    • 谢谢,我可以获取 indexPath.row,但是如何获取单元格内的信息,例如 tableViewCell 之一中的 labelName?我尝试执行以下操作,但事实证明它无法检索数据。 @objc func händlerButtonTapped(sender:UIButton) { let buttonRow = sender.tag let info:infoModel info = infoList[buttonRow] let name = info.labelName print("Name: (name)") } printMessage:(Name: Prototype. infoModel) 它只显示模型名称而不显示值,是否必须使用 didSelectRowAt 来获取单元格内的数据?
    • 不,这取决于您的数据结构,更新您的答案并添加函数 cellForRowAt,我想看看您如何呈现标签( func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell)
    【解决方案3】:

    这是我的 cellForRowAt:

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! contentTableViewCell
    
        let content: contentModel
        content = contentList[indexPath.row]
        contentViewController().getUserProfilePic(userID:content.userID!)
        cell.detailLabelName.text = content.name
        cell.detailLabelTime.text = content.time
        cell.detailTextViewContent.text = content.content
    
        if UserDefaults.standard.data(forKey:content.userID!) != nil {
            cell.detailImageSelfie.image = UIImage(data:UserDefaults.standard.data(forKey:content.userID!)!)
        } else {
            cell.detailImageSelfie.image = #imageLiteral(resourceName: "defaultIcon")
        }
        return cell
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多