Skip to content

Instantly share code, notes, and snippets.

@rajuashok
Created January 14, 2020 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajuashok/abce7497a9273f8e7ed1421090847384 to your computer and use it in GitHub Desktop.
Save rajuashok/abce7497a9273f8e7ed1421090847384 to your computer and use it in GitHub Desktop.
Custom RadioButton for Swift 5
import UIKit
protocol RadioButtonDelegate {
func onClick(_ sender: UIView)
}
class RadioButton: UIButton {
var checkedView: UIView?
var uncheckedView: UIView?
var delegate: RadioButtonDelegate?
var isChecked: Bool = false {
didSet {
setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addTarget(self, action: #selector(onClick), for: UIControl.Event.touchUpInside)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
checkedView?.removeFromSuperview()
uncheckedView?.removeFromSuperview()
removeConstraints(self.constraints)
let view = isChecked == true ? checkedView : uncheckedView
if let view = view {
addSubview(view)
disableAutoResizingMaskTranslationForSubviews()
NSLayoutConstraint.activate([
view.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
}
@objc func onClick(sender: UIButton) {
if sender == self {
delegate?.onClick(self)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment