-3

I have been through few of these tutorial and I cant seem to call my function via button click. I have followed this guy's tutorial but nothing works.

My tableView currently working just great, all Im doing now is adding a button so I could pass data to another view but my button click is not calling its function.

//class IncomeFeedCell: UITableViewCell: 

@IBOutlet var weak button: UIButton!

View Contoller:

// class IncomeFeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource:

// viewDidLoad:
tableView.delegate = self
tableView.dataSource = self

// cellForRowAt indexPath
let cell = self.tableView.dequeueReusableCell(withIdentifier: "IncomeFeedCell") as! IncomeFeedCell
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
cell.configureCell(income: income)
return cell

Now the function to call when tapped:

func buttonPressed(){
  print("Tapped")
}

Simulator:

enter image description here

Have I missed something simple?

Edit:

Apologies for all who and tried to help and got downvoted because I left out more vital information. All this is inside my viewDidLoad in IncomeFeedVC:

super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self

DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in

    /**
     * Sorting the object before looping over
     * Info here: http://stackoverflow.com/questions/41416359/sort-firebase-data-with-queryordered-by-date
     */
    guard let incomeSnap = snapshot.value as? [String:AnyObject] else{

        return
    }

    let sorted = incomeSnap.sorted{($0.0.value["date"] as! Double) > ($0.1.value["date"] as! Double)}

    for snap in sorted {
        if let incomeDict = snap.value as? [String: AnyObject] {
            let key = snap.key
            let income = Income(incomeId: key, incomeData: incomeDict)
            self.incomes.append(income)
        }

    }
    self.tableView.reloadData()
})
Sylar
  • 11,422
  • 25
  • 93
  • 166
  • @HimanshuMoradiya What is and where, please? – Sylar Jan 02 '17 at 05:54
  • cell.button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) this line and func buttonPressed(){ print("Tapped") } funcation – Himanshu Moradiya Jan 02 '17 at 05:55
  • Your question isn't clear. What is the exact problem? What happens when you tap the button? – rmaddy Jan 02 '17 at 05:56
  • @rmaddy When tapped, nothing prints to console. – Sylar Jan 02 '17 at 05:56
  • check if cell.button is nil ??? before adding any action to button – Hrishikesh Jan 02 '17 at 06:02
  • Im confident that this should work. Many tutorials has the same as mine. Im using Swift 3, xcode 8. – Sylar Jan 02 '17 at 06:03
  • 1
    @Hrishikesh If `cell.button` was `nil` there would be crashes trying to use the `nil` reference. – rmaddy Jan 02 '17 at 06:03
  • cell.button is not nil – Sylar Jan 02 '17 at 06:05
  • Could you please share your cell.configureCell(income: income) function. – Dheeraj D Jan 02 '17 at 06:07
  • Move the configureCell line before setting the tag / addTarget code (yes, @DheerajD might be right, you might overwrite the event handler there) – bubuxu Jan 02 '17 at 06:09
  • And to be sure, put a breakpoint inside the `buttonPressed` method. Is the breakpoint reached when a button is tapped? – rmaddy Jan 02 '17 at 06:10
  • Why are you not connecting `IBAction` in `IncomeFeedCell` like `IBOutlet` you have connected! And make sure that your button is not covered by any other view ! – Ketan Parmar Jan 02 '17 at 06:13
  • cell.button.tag = indexPath.row problem is here . all time you got new tag of your button cell so remove it . – Himanshu Moradiya Jan 02 '17 at 06:15
  • @rmaddy Did but the issue is that it's not even attempting to call the function. – Sylar Jan 02 '17 at 06:15
  • @HimanshuMoradiya. There is always a new tag because it is always a new button... There's no reason to delete that if he references the tag later on. – Benjamin Lowry Jan 02 '17 at 06:16
  • but its batter to use outlet instead of tag . – Himanshu Moradiya Jan 02 '17 at 06:17
  • Set the button's tag to row: this is the easiest way to refer to the index of the data array to access the related object for further use. If you don't want to use tag, you can also get the cell by looping sender's superviews, then use `tableView.indexPathForCell` method to get the indexPath. – bubuxu Jan 02 '17 at 06:29
  • I may have a clue here, would `self.tableView.reloadData()` cause an issue elsewhere in my `class`? – Sylar Jan 02 '17 at 06:32
  • @Sylar would you like to update your question and show us your code of the IncomeFeedVC class and IncomeFeedCell class? – bubuxu Jan 02 '17 at 06:41
  • Post updated. Nothing else to add. – Sylar Jan 02 '17 at 06:45

3 Answers3

-2

My ViewController:

class ViewController: UIViewController , UITableViewDelegate,UITableViewDataSource{
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! TestTableViewCell

    cell.bttn.addTarget(self, action: #selector(clickme(sender:)), for: .touchUpInside)
    return cell
}
func clickme(sender: UIButton) {
    print("cliked")
}


}

My UITableViewCell

import UIKit

class TestTableViewCell: UITableViewCell {

@IBOutlet weak var bttn: UIButton!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

Its working fine in my case. Can you remove the "self" in your let cell = self.tableView.dequeueReusableCell(withIdentifier: "IncomeFeedCell") as! IncomeFeedCell line.

theduman
  • 382
  • 1
  • 7
  • 21
  • 1
    How does this explain the problem in the question? Why isn't the `buttonPressed` method being called in the OP's code? – rmaddy Jan 02 '17 at 06:22
  • @maddy I just added a working reference.And OP's code is not working probably of cellForRow function I also suggested what could be wrong in his code. – theduman Jan 02 '17 at 06:25
  • Pretty much all the code in your answer is irrelevant to this question apart from one func. – Benjamin Lowry Jan 02 '17 at 06:25
  • `self` is removed but still the same. Also, I am reloading the `tableView` in `viewDidLoad`. Would that be an issue? – Sylar Jan 02 '17 at 06:39
  • @Sylar no, there is no problem you call tableView.reloadData() in viewDidLoad. – bubuxu Jan 02 '17 at 06:43
-4

your button tapped function should be like this:

  func buttonPressed(sender: UIButton)
  {

  let buttonTag = sender.tag// you can check tag like this

  }
Sagar Snehi
  • 398
  • 3
  • 13
  • 3
    The `sender` parameter is not needed. Adding this doesn't answer the question. – rmaddy Jan 02 '17 at 05:59
  • 1
    Someone said the `sender` parameter is not needed, yes, you don't need to provide any parameter to an event handler, but it's a bad programming behaviour. You should always pass in `sender` to any event handler for UIControl even you don't use it. – bubuxu Jan 02 '17 at 06:05
  • @sagar his func buttonPressed(sender: UIButton) method is not calling. – Dheeraj D Jan 02 '17 at 06:11
  • agreed with @bubuxu sender should be present is good programming but not mandatory – Wagh Jan 02 '17 at 06:12
  • That's great, but that doesn't necessarily solve OP's problems. – Benjamin Lowry Jan 02 '17 at 06:27
-4

Can you please try

cell.button.addTarget(self, action: #selector(IncomeFeedVC.buttonPressed(_:)), for: .touchUpInside)

Also below function should be implemented in IncomeFeedVC class

func buttonPressed(_ sender: AnyObject){
  print("Tapped")
}
Wagh
  • 2,678
  • 1
  • 25
  • 29