lundi 12 août 2019

ValueChange function executing twice

I have the following function in my CheckBox class for valueChanged:

public var valueChanged: ((_ isChecked: Bool) -> Void)?
    @objc private func handleTapGesture(recognizer: UITapGestureRecognizer) {
        isChecked = !isChecked
        valueChanged?(isChecked)
        sendActions(for: .valueChanged)

        if useHapticFeedback {
            // Trigger impact feedback.
            feedbackGenerator?.impactOccurred()

            // Keep the generator in a prepared state.
            feedbackGenerator?.prepare()
        }
    }

In my PostTableViewCell class, I have two CheckBox UI Elements:

   @IBOutlet weak var downVote: Checkbox!    @IBOutlet weak var checkbox: Checkbox!

In this class, I also have the following relevant code:

var downcheck = false

var boxcheck = false

override func awakeFromNib(){
suoer.awakeFromNib
checkbox.addTarget(self, action: #selector(checkboxValueChanged(sender:)), for: .valueChanged)
downVote.addTarget(self, action: #selector(checkboxValueChanged(sender:)), for: .valueChanged)
}

@objc func checkboxValueChanged(sender: Checkbox) { print("checkbox value change: (sender.isChecked)")

}

Finally, I have the following function for clicking on checkbox or downVote:

 func set(post:Post) {checkbox.valueChanged = { (value) in
            print("checkbox value change: \(value)")
            self.boxcheck = value
            if self.boxcheck == true {
                //stuff
            }

            else if self.boxcheck == false {
                //stuff
        }


        downVote.valueChanged = { (value) in
            print("downVote value change: \(value)")
            self.downcheck = value
            if self.downcheck == true {
                //stuff
            }

            else if self.downcheck == false {
               //stuff
            }
        }
    }
}

When I click the upvote box, I upvote twice and get the text in console:

checkbox value change: true

checkbox value change: true

If I then hit the downvote box, I get:

downVote value change: true

checkbox value change: true

I should get checkbox = true when I hit checkbox, and downvote = true when I hit downvote. How do I fix these extra executions?




Aucun commentaire:

Enregistrer un commentaire