Simple Checkbox Component in iOS

Leela Krishna
Swift India
Published in
2 min readApr 21, 2019

Add one more custom UIComponent in your iOS Arsenal.

Before we go,

I wanted to create some UIComponent like check box, but so far I used UIButton with images in my projects. When I search for more optimised solution, I come across an open source project for the same. I took inspiration from this project, and finally created the required component. It is so simple and optimised, so we can use all iOS projects. You can check the above mentioned open source project here, created by Beau Nouvelle.

  1. Create an IBDesignable Class For Checkbox, I named it as Checkbox.
  2. Define an enum for Style, so we can have an api to choose the appearance for check mark, like tick, cross, or circle etc.
  3. Define an enum for BorderStyle, So we can customise the Checkbox appearance with border-style property, by giving corner radius or giving this enum cases.
  4. Define variables for the above created two enum types, and as well as the following ones, so we can use them to render the component.
  • borderWidth: CGFloat, To set the border width for our checkbox component
  • checkmarkSize: CGFloat, the size for rendering
  • uncheckedBorderColor: UIColor, colour for unchecked state
  • checkedBorderColor: UIColor, colour for checked state
  • checkmarkColor: UIColor, to render the checked state inner styled component
  • checkboxBackgroundColor: UIColor!
  • increasedTouchRadius: CGFloat, to expand the touchable area, as in general check box sizes are small as compared to other UIElements in iOS
  • useHapticFeedback: Bool, from iPhone7, we have haptic feedback engines in devices, as device vibrates or gives some kind of haptic feedback to the user on certain actions. Check for the Apple documentation on it more here and here.
  • isChecked: Bool = false, is an observable property, so we can render the change in check box’s state by using it.
  • feedbackGenerator, is used to provide haptic feed back on state changes for the component.

5. Define the initialisers for this class.

6. Override touches begin, touches ended, draw methods of UIView, so we can define the functionality accordingly.

7. Define the required helper methods, to draw the inner components on it is selected like tick, circle, cross etc depending on the above mentioned style property.

Check the following Gist, as the comments will help you understanding what the functions do.

Usage :

You can download the sample project from here.

— — — — — — — — — *********************** — — — — — — — — —

You can contact / follow me on twitter & linkedIn accounts.

Thanks for reading…

****************************!!!See you!!!****************************

--

--