I have subclassed UIButton to get a checkbox :
let kCheckedImage = UIImage(named: "checked")!
let kUncheckedImage = UIImage(named: "unchecked")!
@IBDesignable
class CheckBox: UIButton {
@IBInspectable public var isChecked: Bool = false
@IBInspectable public var image: UIImage?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
image = kUncheckedImage
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func draw(_ rect: CGRect) {
image?.draw(in: rect)
}
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
}
@objc func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
if isChecked == true {
self.setImage(kCheckedImage, for: UIControl.State.normal)
} else {
self.setImage(kUncheckedImage, for: UIControl.State.normal)
}
}
self.setNeedsDisplay()
}
}This works werll when I insert a CheckBox directly in a view in the storyboard.
Problam is when I try to inlcude such button in a xib (for UITableViewCell): the button works correctly, but I cannot get it drawn in IB.
I have tried to declare the UITableViewCell as IBDesignable, I have tried to include override func prepareForInterfaceBuilder(), no way.
Here is the code of the UITableViewCell associated to the xib:
class CheckCell: UITableViewCell {
@IBOutlet weak var checked: CheckBox! // The checked button
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I don't understand at all why, but it works now, with the same code ! The checkboxes are drawn in the UITableViewCell.xib.
Could what I did in between be the cause ? :
- I created a new project, copied the code for CheckBox, cretaed some views with it, including a UITableViewCell xib
- Closed XCode
- made a copy of the project
- opened the project as well as this copy in XCode
… and magically it works.
So, what was XCode doing behind the scene will probably remain a mystery to me.