-2

I have a custom cell that has a stackview that contains several buttons. I need to be able to show each button depending on a data item. for example in one cell three buttons will appear, in another 4 different buttons appear, in another all buttons. The cell looks like this:

enter image description here

As a test, I tried the code below to set the buttons:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "doctrineCell", for: indexPath) as! DoctrineCell

    let doctrine = doctrines[indexPath.row]
    cell.doctrineLabel.text = doctrine.doctrineText!

    cell.bofmButton.isHidden = true
    cell.otButton.isHidden = true
    cell.ntButton.isHidden = true
    cell.ldaButton.isHidden = true
    cell.ldpButton.isHidden = true
    cell.pbutton.isHidden = true
    cell.jsbutton.isHidden = true
    cell.allButton.isHidden = true

    cell.ldaButton.isHidden = false
    cell.ldpButton.isHidden = false
    cell.pbutton.isHidden = false    

    return cell
}

When I run the app all buttons show.

How do I control what buttons are displayed?

lascoff
  • 1,321
  • 4
  • 17
  • 35
  • have you made sure all the outlets are properly set? – jacob bullock Jan 25 '17 at 02:11
  • Show the definition of DoctrineCell please. – matt Jan 25 '17 at 02:21
  • Oh, one more very important thing: put a breakpoint on any of that code and make sure it is even running. There is a very real possibility, if you've set this up wrong, that it never runs, so let's eliminate that. – matt Jan 25 '17 at 02:23
  • There's nothing wrong with the above code. The problem probably rests in how the cell was created and/or how the outlets were established to these buttons. Or, if these buttons are some special custom subclass, perhaps there's some problem in that code. But the problem is not in the `cellForRowAt` code... – Rob Jan 25 '17 at 02:34
  • Thanks the issue was in the outlets... I appreciate the help – lascoff Jan 25 '17 at 04:26

1 Answers1

-3

Instead of ctrl+dragging to create an outlet you can ctrl+drag to create an Outlet Collection, which is an array of buttons. Now you can access them in a for loop.

cell.buttons.forEach {$0.isHidden = true}
cell.buttons[8].isHidden = false
cell.buttons[9].isHidden = false
cell.buttons[10].isHidden = false

For whatever reason interface builder does not guarantee the order of the buttons in the array so in awakeFromNib sort the array by x order:

cell.buttons.sort {$0.0.frame.origin.x < $0.1.frame.origin.x }
Josh Homann
  • 15,933
  • 3
  • 30
  • 33