Reputation: 241
I have a custom tableviewcell and I have button inside the cell when I click on the button the next viewcontroller does not show he content , but if I click on cell then clicking the button the next view controller showing the right content here is my code :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
cell.label.text = numberArray[indexPath.row]
cell.button.tag = indexPath.row
cell.button.addTarget(self,action:#selector(TableViewController.someAction(sender:)),
for:.touchUpInside)
return cell
}
here is my button action :
func someAction(sender : UIButton){
self.performSegue(withIdentifier: "showDetail", sender: self)
}
and here is my segue function :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow
{
(segue.destination as! ViewController).number = numberArray[indexPath.row]
}
}
}
Upvotes: 1
Views: 742
Reputation: 72460
The issue is that in prepare(for:sender:)
you are getting indexPath
using indexPathForSelectedRow
now if you directly click the button then cell with not selected what you need is to pass the indexPath
of cell with performSegue(withIdentifier:sender:)
.
func someAction(sender: UIButton) {
let point = sender.superview?.convert(sender.center, to: self.tableView)
if let indexPath = self.tableView.indexPathForRow(at: point!) {
//pass indexPath as sender with performSegue
self.performSegue(withIdentifier: "showDetail", sender: indexPath)
}
}
Now in prepare(for:sender:)
cast the sender
to indexPath
and you all good to go.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = sender as? IndexPath
{
(segue.destination as! ViewController).number = numberArray[indexPath.row]
}
}
}
Note: It is batter if you ignored to use tag
.
Upvotes: 4
Reputation: 615
Try this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
(segue.destination as! ViewController).number = numberArray[sender.tag]
}
}
Upvotes: 0
Reputation: 3494
You have to use custom cell and follow the steps:
Upvotes: 0