Search code examples
iosswiftcustom-keyboard

How to implement custom fonts to a custom keyboard to use on other apps?


I am coding in Swift 5.0. I want to create an app where users can download custom fonts and use them in any app. I am using a keyboard extension to do that.

Here is my code

class KeyboardViewController: UIInputViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    let button = createButton(title: "A")
    self.view.addSubview(button)
}

func createButton(title: String) -> UIButton {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 0,y: 0,width: 20,height: 20)
    button.setTitle(title, for: .normal)
    button.sizeToFit()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont(name: "Montague.ttf", size: 15)
    button.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
    button.setTitleColor(UIColor.darkGray, for: .normal)
    button.addTarget(self, action: #selector(didTapButton(sender:)), for: .touchUpInside)

    return button
}

@objc func didTapButton(sender: AnyObject) {
     let button = sender as! UIButton
     button.titleLabel?.font = UIFont(name: "Montague.ttf", size: 15)
     let title = button.title(for: .normal)
     textDocumentProxy.insertText(title!)
}

Here is the output.result

So my question is how to make a keyboard button appearance and output in the font I want?


Solution

  • You can customize your button's title font using the titleLabel attribute of button.

    button.titleLabel?.font = UIFont(name: "YourCustomFont", size: 10.0)
    

    You can't change font on the output as app developers decide what fonts they want to use in their app AFAIK.

    Edit: Well I didn't know what you meant by setting the output, for more info about the app you linked to please read this SO post: How to Insert NSAttributedString using custom keyboard extension?

    tl;dr: You can't set a custom font, those apps use unicodes and if you choose to, you should too.