Mike Schmidt Mike Schmidt - 1 year ago 246
iOS Question

Check Box Selected Action in Swift?

I am using M13Checkbox, and you can look at the Github page here. In my table view function, I assign a M13 Checkbox to each cell's checkbox variable. The variable looks like this

var checkbox = M13Checkbox()
in my custom cell class.

This is what the code where I define the checkbox inside the table view looks:

cell.checkbox = M13Checkbox(frame: CGRect(x: 15.0, y: (cell.center.y)-22.0, width: 20.0, height:20.0))

My question is how do I have an action occur when a user presses a checkbox? I want another view or a popover to come up when a checkbox is clicked. Is that possible with the way I have it set up? What code do I need to add?

Answer Source

M13Checkbox is derived from UIControl, so you can use addTarget function to add a handler to an event.

cell.checkBox.tag = indexPath.row

cell.checkBox.addTarget(self, action: #selector(YourClassName.onValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)


func onValueChanged(sender : AnyObject?)
  if let checkBox = sender.view as? M13Checkbox
    let row = checkBox.tag
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download