I am using a UIButton of custom type and what I want is use it like a toggle switch with the change of image. Like when it is clicked if previously it was not in selected mo
In order to do so we can use UIButton Subclass:
class UIToggleButton: UIButton {
fileprivate let onImage: UIImage
fileprivate let offImage: UIImage
fileprivate let target: AnyObject
fileprivate let onAction: Selector
fileprivate let offAction: Selector
var isOn: Bool {
didSet {
let image = isOn ? onImage : offImage
setImage(image, for: UIControlState())
}
}
init(onImage: UIImage,
offImage: UIImage,
target: AnyObject,
onAction: Selector,
offAction: Selector)
{
isOn = false
self.onImage = onImage
self.offImage = offImage
self.target = target
self.onAction = onAction
self.offAction = offAction
super.init(frame: CGRect.zero)
setImage(offImage, for: UIControlState())
addTarget(self, action: #selector(UIToggleButton.tapAction), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func tapAction() {
let sel = isOn ? onAction : offAction
isOn = !isOn
_ = target.perform(sel)
}
}