Detecting which UIButton was pressed in a UITableView

前端 未结 26 3276
小蘑菇
小蘑菇 2020-11-22 00:40

I have a UITableView with 5 UITableViewCells. Each cell contains a UIButton which is set up as follows:

- (UITableView         


        
26条回答
  •  情歌与酒
    2020-11-22 01:00

    SWIFT 2 UPDATE

    Here's how to find out which button was tapped + send data to another ViewController from that button's indexPath.row as I'm assuming that's the point for most!

    @IBAction func yourButton(sender: AnyObject) {
    
    
         var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
            let indexPath = self.tableView.indexPathForRowAtPoint(position)
            let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
            UITableViewCell
            print(indexPath?.row)
            print("Tap tap tap tap")
    
        }
    

    For those who are using a ViewController class and added a tableView, I'm using a ViewController instead of a TableViewController so I manually added the tableView in order to access it.

    Here is the code for passing data to another VC when tapping that button and passing the cell's indexPath.row

    @IBAction func moreInfo(sender: AnyObject) {
    
        let yourOtherVC = self.storyboard!.instantiateViewControllerWithIdentifier("yourOtherVC") as! YourOtherVCVIewController
    
    
    
        var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
        let indexPath = self.tableView.indexPathForRowAtPoint(position)
        let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
        UITableViewCell
        print(indexPath?.row)
        print("Button tapped")
    
    
        yourOtherVC.yourVarName = [self.otherVCVariable[indexPath!.row]]
    
        self.presentViewController(yourNewVC, animated: true, completion: nil)
    
    }
    

提交回复
热议问题