简体   繁体   中英

Programmatically generated button not performing action

I am trying to add some buttons dynamically in UITableViewCell.I have created method "tappedButton" which is supposed to call when any of those buttons get clicked but its not working properly. I need to press 3 or 4 times and then hardly the action happens.Can anyone suggest me a better way to do this.

    func tappedButton(sender: UIButton!) {
            print("tapped button---->"+(sender.titleLabel?.text)!)
            self.performSegueWithIdentifier("web", sender: self)
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! MagazineTableViewCell
                 // headings is global variable , an array of string
                 for td in headings {
                    let button:UIButton = UIButton(frame: CGRectMake(0, t, 500, 26))
                    t+=36
                    button.setTitle(td,forState: UIControlState.Normal)
                    let black=hexStringToUIColor("#000000")
                    let white=hexStringToUIColor("#ffffff")
                    button.backgroundColor = black
                    button.setTitleColor(white, forState: UIControlState.Normal)
                    button.addTarget(self, action: #selector(MainTableViewController.tappedButton(_:)), forControlEvents: UIControlEvents.AllTouchEvents)
                    // searchView is a black UIView in which I dynamically add buttons
                    cell.searchView.addSubview(button)
                  }

         return cell
    }

You should add your Button in your cell's subclass. Then addTarget in your cellforRowAtIndexParh. Please try it and let me know. + change in your addTarget with .touchDown Instead of .AllTouchEvents

You'd better add UIButton into your prototype cell and then just add

yourButton.hidden = true 

if you want it to be hidden. Note that you should add

yourButton.hidden = false 

after

let cell = ..

to make it work fine when cells are reused.

Let's try to update the cellForRowAtIndexPath method like below.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! MagazineTableViewCell

        //remove existing buttons
        for subView in cell.searchView.subviews{

            subView.removeFromSuperview()
        }

        // headings is global variable , an array of string
        for td in headings {
            let button:UIButton = UIButton(frame: CGRectMake(0, t, 500, 26))
            t+=36
            button.setTitle(td,forState: UIControlState.Normal)
            let black=hexStringToUIColor("#000000")
            let white=hexStringToUIColor("#ffffff")
            button.backgroundColor = black
            button.setTitleColor(white, forState: UIControlState.Normal)
            button.addTarget(self, action: #selector(MainTableViewController.tappedButton(_:)), forControlEvents: UIControlEvents.touchUpInside)
            // searchView is a black UIView in which I dynamically add buttons
            cell.searchView.isUserInteractionEnabled = true
            cell.searchView.addSubview(button)
        }

        return cell
    }

You are trying to add the button to cell in cellForRowAtIndexPath method in which the buttons will be overlapped whenever cellForRowAtIndexPath called. So first yo should remove the existing buttons from searchView and add your dynamic(headings) buttons in for loop.

I have replicated your scenario in a basic project:

class ViewController: UIViewController {
  @IBOutlet weak var tableView: UITableView!

  let numberOfButtons = 3
  var currentButtonYPosition: CGFloat = 0

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    currentButtonYPosition = 0

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell

    for index in 0..<numberOfButtons {
      let button = UIButton()
      button.frame = CGRectMake(0, currentButtonYPosition, tableView.frame.width, 30)
      button.backgroundColor = UIColor.redColor()
      button.setTitle(String(index), forState: .Normal)
      button.addTarget(self, action: #selector(buttonWasTapped(_:)), forControlEvents: .TouchUpInside)

      cell.innerView.addSubview(button)

      currentButtonYPosition += 40
    }

    return cell
  }

  func buttonWasTapped(button: UIButton) {
    print("button \(button.currentTitle!) was tapped")
  }
}

Result

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