I have a UIButton, and the expected behavior is when it is tapped, it should be have the blue background color, and when untapped, it should be white. However, I always have to double tap it on the first try for it to become selected... why is that?
class CheckmarkCell: UITableViewCell {
static let reuseIdentifier = String(describing: CheckmarkCell.self)
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var yesButton: UIButton!
private weak var delegate: CheckmarkCellDelegate?
private var value: Bool?
public func configure(title: String, value: Bool?, delegate: CheckmarkCellDelegate? = nil) {
self.titleLabel.text = title
self.value = value
self.delegate = delegate
self.yesButton.layer.masksToBounds = true
self.yesButton.layer.cornerRadius = self.yesButton.frame.width / 2
self.yesButton.layer.borderWidth = 1.0
self.yesButton.layer.borderColor = UIColor.NBABlue?.cgColor
self.yesButton.backgroundColor = UIColor.white
// This is the dot
self.yesButton.tintColor = UIColor.clear
// This block of code saves the values. If it is removed, when you scroll, values will all be deselected and false.
switch self.value {
case true:
// This is the saved state
self.yesButton.backgroundColor = UIColor.NBABlue
self.yesButton.tintColor = UIColor.clear
// Deselected, should e white.
case false:
self.yesButton.backgroundColor = UIColor.white
self.yesButton.tintColor = UIColor.clear
default:
break
}
}
@IBAction func buttonTapped(_ sender: UIButton) {
if sender.isSelected {
yesButton.isSelected = false
// The selected state
self.yesButton.backgroundColor = UIColor.NBABlue
self.yesButton.tintColor = UIColor.clear
if self.value == nil || self.value == false {
self.value = true
self.delegate?.checkmarkCell(self, selectedValue: self.value!)
}
} else {
yesButton.isSelected = true
self.yesButton.backgroundColor = UIColor.white
self.yesButton.tintColor = UIColor.clear
if self.value == nil || self.value == true {
self.value = false
self.delegate?.checkmarkCell(self, selectedValue: self.value!)
}
}
}
}
CodePudding user response:
Cells are reused add this also inside configure
self.yesButton.tintColor = UIColor.clear // below this
self.yesButton.isSelected = self.value
CodePudding user response:
For remove blue background you have to clear tint colour from storyboard.
In section file IBAction write this line.
sender.isSelected = !sender.isSelected