I'm trying to toggle an UISwitch through an objc function, however the switch is not recognizing the UITapGestureRecognizer
I implemented.
StatusAvailabilityCell
// MARK: - Properties
lazy var toggle: UISwitch = {
let toggle = UISwitch()
toggle.isOn = false
toggle.isEnabled = true
toggle.onTintColor = .darkPurpleTint
return toggle
}()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureUI()
handleToggle()
}
// MARK: - Selectors
@objc func toggleSwitch(_ sender: UISwitch) {
if sender.isOn == true {
sender.tintColor = .darkPurpleTint
sender.setOn(true, animated: true)
} else {
sender.tintColor = .white
sender.setOn(false, animated: true)
}
}
// MARK: - Helper Functions
fileprivate func handleToggle() {
let tap = UITapGestureRecognizer(target: self, action: #selector(toggleSwitch(_:)))
tap.numberOfTapsRequired = 1
toggle.addGestureRecognizer(tap)
}
StatusAvailabilityController
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifiers.StatusAvailabilityCell, for: indexPath) as! StatusAvailabilityCell
cell.selectionStyle = .none
cell.separatorInset = UIEdgeInsets.init(top: 0, left: cell.bounds.size.width, bottom: 0, right: 0)
return cell
}
I have tried to do an addTarget
implementation to the UISwitch instead of an UITapGestureRecognizer
. I also tried to implement setOn()
but it still isn't switching on and off. Thank you in advance.