writing code

Replicating keys from UIKit

In creating my own in-app keyboard, for one of my applications, I stumbled on a problem - how does one replicate the key from the typical iOS keyboard?

So analyzing it a bit, it seems like the button is styled like this:

let button = UIButton()
button.setTitle("touch me", for: .normal)
button.backgroundColor = .white
button.layer.cornerRadius = 4
button.layer.shadowColor =
button.layer.shadowRadius = 0
button.layer.shadowOffset = CGSize(width: 0, height: 1)
button.layer.shadowOpacity = 0.25

So lets makes ourselves a subclass of UIButton, so we don't have to write this every time.

class KeyboardButton: UIButton {
    override func didMoveToSuperview() {
        setTitleColor(.black, for: .normal)
        backgroundColor = .white
        layer.cornerRadius = 4
        layer.shadowColor =
        layer.shadowRadius = 0
        layer.shadowOffset = CGSize(width: 0, height: 1)
        layer.shadowOpacity = 0.25

As you can see, I use didMoveToSuperview() to style the button, I do this because of how I use it to create a keyboard, where I do not wanna have an initializer and thereby need to handle explicit sizing (you can read more about this later).

But what about handling touches? So the button changes background when we touch it? Well this is also one of the benefits of subclassing UIButton! We can just observe the highlight!

override var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? .lightgray : .white

Putting this in the class, we now have recreated the classic iOS key from the keyboard! Use it as any other button to add title, actions and so on.

Update: see my full implementation, with formatters and hit-observers, over at my GitHub.