elkin sepulveda elkin sepulveda - 3 months ago 32
Swift Question

Swift Check , Unchecked Button

I have two modified buttons to be a checkbox with a subclass, the checkbox is

siCheckbox
and
noCheckbox
. if
siCheckbox
is checked the other will be unchecked.

The problem is , if i press
siCheckBox
again will set
noCheckbox
checked and
siCheckBox
unchecked

this is my code

import UIKit
class Paso1: UIViewController, CheckBoxDelegate {

@IBOutlet weak var siCheckBox: CheckBox!
@IBOutlet weak var noCheckBox: CheckBox!

override func viewDidLoad() {
super.viewDidLoad()

self.siCheckBox.delegate = self
self.noCheckBox.delegate = self
}

func checkBoxDidChange(checkbox: CheckBox) {
if checkbox == self.siCheckBox {
self.noCheckBox.isChecked = !checkbox.isChecked

} else {
self.siCheckBox.isChecked = !checkbox.isChecked

}
}


and this is the subclass for the buttons checkbox

protocol CheckBoxDelegate {
func checkBoxDidChange(checkbox: CheckBox) -> Void
}
import UIKit

class CheckBox: UIButton {

// Images
let checkedImage = UIImage(named: "check-greenb")! as UIImage
let uncheckedImage = UIImage(named: "check-baseb")! as UIImage

var delegate: CheckBoxDelegate?
// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
} else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}

override func awakeFromNib() {
self.addTarget(self, action: #selector(CheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}

func buttonClicked(sender: UIButton) {
isChecked = !isChecked
self.delegate?.checkBoxDidChange(self)
}}


is there any examples or a better way to do this?

Answer

If you don't want your button to change its checked property if it is already checked, just add conditional logic in your buttonClicked function.

func buttonClicked(sender: UIButton) {
    if !isChecked {
        isChecked = !isChecked
        self.delegate?.checkBoxDidChange(self)
    }
}
Comments