-1

I have a xib file with 4 buttons and each button has a function which it has to start when clicked. The function has to fetch data and after it has fetched data it should perform a segue. I am only allowed to use a nib which is of type UITableViewCell and show it in a tableview inside a viewcontroller.

Is it possible to get each button to start the required function when tapped in the tableviewcell, if so how do i go about it.

I have looked at questions similar to mine for days and tried all the suggested solutions and they arent working e.g.

enter image description here

Show ViewController from XIB-file-Button - Swift

Perform segue from button in XIB

Swift - Segue from Button inside a cell

Perform segue from button in XIB

Perform Segue from Xib programmatically

Erent
  • 571
  • 6
  • 15
  • 29

1 Answers1

1

Sure, it's pretty simple in the code to have the event passed in the action and then access the index path.

First add the target to your button.

button.addTarget(self, action: #selector(someAction(_:event:)), for: .touchUpInside)

Then use this code to start your action.

@objc func someAction(_ button: UIButton, event: UIEvent) {
    guard let location = event.allTouches?.first?.location(in: tableView),
        let indexPath = tableView?.indexPathForItem(at: location)
        else {
            return
    }

    // TODO: fetch data

    performSegue(withIdentifier: "mySegueID", sender: button)
}

Also if your data is async, you could use something like PromiseKit. https://github.com/mxcl/PromiseKit

cnotethegr8
  • 7,342
  • 8
  • 68
  • 104