I have a password UICollectionViewCell
with a UITextField
to enter the password. I want to have a button where the user can change the isSecureTextEntry property.
My Code
private lazy var button: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.addTarget(self, action: #selector(toggle), for: .touchUpInside)
return view
}()
@objc func toggle(_ sender: UIButton) {
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
}
Set Up Cell
self.toggle(button)
However, my button image is not changing.
CodePudding user response:
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
You're setting for normal state on one side and for selected state on the other.
Try this:
button.setImage((sender.isSelected ? unSecureImage : secureImage), for: .normal)
CodePudding user response:
Can you try like this,
Setting the image for normal and selected state
On tapping the button changing the isSelected state of the button
private lazy var button: UIButton = { let view = UIButton() view.translatesAutoresizingMaskIntoConstraints = false view.setImage(secureImage, for: .normal) view.setImage(unSecureImage, for: .selected) view.addTarget(self, action: #selector(toggleAction), for: .touchUpInside) return view }() @objc func toggleAction(_ sender: UIButton) { sender.isSelected.toggle() }