简体   繁体   中英

Swift: Table View Cell perform segue to two different destinations

My question: I wanna perform segue to two different destinations in a table view cell. One is directing destination "A" by clicking the cell which handled by didSelectRowAt, Another one is directing to destination "B" by clicking the button inside the cell, for example, the labelName.

For destiation "B", I have try to use (btn.addTarget), but it cannot add parameters, so the destinatin view controller do not know the which cell was being clicked.

Any suggestion?

you can use button.tag and assign the tag of every button with your indexpath.row

button.tag = indexPath.row
button.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchUpInside)

func btnClick(sender:UIButton) {
    let buttonRow = sender.tag
}

for swift 4 :

  button.addTarget(self, action: #selector(händlerButtonTapped), for: .touchUpInside)

    @objc func händlerButtonTapped(sender:UIButton) {
       let buttonRow = sender.tag
    }

You can Get the indexPath of your selected TableviewCell in your btnClick function by using this.

let index = self.tableview.indexPathForSelectedRow

Now by doing this you can solve this problem you mentioned.

the destinatin view controller do not know the which cell was being clicked

Here is my 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM