我有一个密码UICollectionViewCell
和一个UITextField
来输入密码。我想有一个按钮,用户可以改变isSecureTextEntry属性。
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)
}
设置单元格
self.toggle(button)
但是,我的按钮图像没有改变。
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
一边设置为正常状态,另一边设置为选择状态。
试试这个:
button.setImage((sender.isSelected ? unSecureImage : secureImage), for: .normal)
你能不能这样试试,
-
设置图像为正常和选中状态
-
点击按钮改变按钮的isSelected状态
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() }