简体   繁体   中英

How can I programmatically add pages to my custom keyboard as well as categories (similar to Apple emoji Keyboard)?

How can I programmatically add pages to my custom keyboard as well as categories (similar to Apple emoji Keyboard)?

How can I add pages (swipe right for more emojis - in this case text) to my custom keyboard like Apple's emoji keyboard in Swift programatically?

I was also wondering how apple creates their custom categories for their emoji's like the flower and recents? I'm assuming they use arrays, but how would I go about doing that programatically in Swift?

import UIKit

class KeyboardViewController: UIInputViewController {

    @IBOutlet var nextKeyboardButton: UIButton!

    override func updateViewConstraints() {
        super.updateViewConstraints()

        // Add custom view sizing constraints here
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let buttonTitles1 = ["TEXT0"]
        let buttonTitles2 = ["TEXT1"]
        let buttonTitles3 = ["TEXT2"]
        let buttonTitles4 = ["🌐", "🏃", "🙇", "👫", "💰", "🙈", "Aa", "⌫"]

        var row1 = createRowOfButtons(buttonTitles1)
        var row2 = createRowOfButtons(buttonTitles2)
        var row3 = createRowOfButtons(buttonTitles3)
        var row4 = createRowOfButtons(buttonTitles4)

        self.view.addSubview(row1)
        self.view.addSubview(row2)
        self.view.addSubview(row3)
        self.view.addSubview(row4)

        row1.setTranslatesAutoresizingMaskIntoConstraints(false)
        row2.setTranslatesAutoresizingMaskIntoConstraints(false)
        row3.setTranslatesAutoresizingMaskIntoConstraints(false)
        row4.setTranslatesAutoresizingMaskIntoConstraints(false)

        addConstraintsToInputView(self.view, rowViews: [row1, row2, row3, row4])
    }

    func createRowOfButtons(buttonTitles: [NSString]) -> UIView {

        var buttons = [UIButton]()
        var keyboardRowView = UIView(frame: CGRectMake(0, 0, 320, 50))

        for buttonTitle in buttonTitles{

            let button = createButtonWithTitle(buttonTitle)
            buttons.append(button)
            keyboardRowView.addSubview(button)
        }

        addIndividualButtonConstraints(buttons, mainView: keyboardRowView)

        return keyboardRowView
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated
    }

    override func textWillChange(textInput: UITextInput) {
        // The app is about to change the document's contents. Perform any preparation here.
    }

    override func textDidChange(textInput: UITextInput) {
        // The app has just changed the document's contents, the document context has been updated.

        var textColor: UIColor
        var proxy = self.textDocumentProxy as UITextDocumentProxy
        if proxy.keyboardAppearance == UIKeyboardAppearance.Dark {
            textColor = UIColor.whiteColor()
        } else {
            textColor = UIColor.blackColor()
        }
    }

    func createButtonWithTitle(title: String) -> UIButton {

        let button = UIButton.buttonWithType(.System) as UIButton
        button.frame = CGRectMake(0, 0, 20, 20)
        button.setTitle(title, forState: .Normal)
        button.sizeToFit()
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTranslatesAutoresizingMaskIntoConstraints(false)
        button.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)

        button.addTarget(self, action: "didTapButton:", forControlEvents: .TouchUpInside)

        return button
    }

    func didTapButton(sender: AnyObject?) {

        let button = sender as UIButton
        var proxy = textDocumentProxy as UITextDocumentProxy

        if let title = button.titleForState(.Normal) {
            switch title {
            case "TEXT1" :
                proxy.insertText("hi")
            case "ENTER" :
                proxy.insertText("\n")
            case "TEXT 2" :
                proxy.insertText("YOLO")
            case "🌐" :
                self.advanceToNextInputMode()
            case "TEXT0" :
                proxy.insertText("hello")

            case "⌫" :
                proxy.deleteBackward()
            default :
                proxy.insertText("WUT?!")
            }
        }
    }

    func addIndividualButtonConstraints(buttons: [UIButton], mainView: UIView){

        for (index, button) in enumerate(buttons) {

            var topConstraint = NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: mainView, attribute: .Top, multiplier: 1.0, constant: 1)

            var bottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: mainView, attribute: .Bottom, multiplier: 1.0, constant: -1)

            var rightConstraint : NSLayoutConstraint!

            if index == buttons.count - 1 {

                rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: mainView, attribute: .Right, multiplier: 1.0, constant: -1)

            }else{

                let nextButton = buttons[index+1]
                rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: nextButton, attribute: .Left, multiplier: 1.0, constant: -1)
            }

            var leftConstraint : NSLayoutConstraint!

            if index == 0 {

                leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: mainView, attribute: .Left, multiplier: 1.0, constant: 1)

            }else{

                let prevtButton = buttons[index-1]
                leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: prevtButton, attribute: .Right, multiplier: 1.0, constant: 1)

                let firstButton = buttons[0]
                var widthConstraint = NSLayoutConstraint(item: firstButton, attribute: .Width, relatedBy: .Equal, toItem: button, attribute: .Width, multiplier: 1.0, constant: 0)

                widthConstraint.priority = 800
                mainView.addConstraint(widthConstraint)
            }

            mainView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint])
        }
    }

    func addConstraintsToInputView(inputView: UIView, rowViews: [UIView]){

        for (index, rowView) in enumerate(rowViews) {
            var rightSideConstraint = NSLayoutConstraint(item: rowView, attribute: .Right, relatedBy: .Equal, toItem: inputView, attribute: .Right, multiplier: 1.0, constant: -1)

            var leftConstraint = NSLayoutConstraint(item: rowView, attribute: .Left, relatedBy: .Equal, toItem: inputView, attribute: .Left, multiplier: 1.0, constant: 1)

            inputView.addConstraints([leftConstraint, rightSideConstraint])

            var topConstraint: NSLayoutConstraint

            if index == 0 {
                topConstraint = NSLayoutConstraint(item: rowView, attribute: .Top, relatedBy: .Equal, toItem: inputView, attribute: .Top, multiplier: 1.0, constant: 0)

            }else{

                let prevRow = rowViews[index-1]
                topConstraint = NSLayoutConstraint(item: rowView, attribute: .Top, relatedBy: .Equal, toItem: prevRow, attribute: .Bottom, multiplier: 1.0, constant: 0)

                let firstRow = rowViews[0]
                var heightConstraint = NSLayoutConstraint(item: firstRow, attribute: .Height, relatedBy: .Equal, toItem: rowView, attribute: .Height, multiplier: 1.0, constant: 0)

                heightConstraint.priority = 800
                inputView.addConstraint(heightConstraint)
            }
            inputView.addConstraint(topConstraint)

            var bottomConstraint: NSLayoutConstraint

            if index == rowViews.count - 1 {
                bottomConstraint = NSLayoutConstraint(item: rowView, attribute: .Bottom, relatedBy: .Equal, toItem: inputView, attribute: .Bottom, multiplier: 1.0, constant: 0)

            }else{

                let nextRow = rowViews[index+1]
                bottomConstraint = NSLayoutConstraint(item: rowView, attribute: .Bottom, relatedBy: .Equal, toItem: nextRow, attribute: .Top, multiplier: 1.0, constant: 0)
            }

            inputView.addConstraint(bottomConstraint)
        }
    }
}

I would try to avoid that method. I tried to do the same as you did because the page-control element ( the dots on the emoji keyboard made by Apple to switch pages) doesn't seem to work for my custom keyboard. I create a xib file and dragged the element onto the xib file, the file hosted all my buttons (this could be done programmatically of course), but instead of showing up on my simulator it made my keyboard disappear. I implemented the page-control element programmatically and got the same result. I have a different way of doing it this time:

  • Make a button that switches the current buttons, or a button that modifies the values and image of previous buttons on the keyboard.

I find this way is much more easier. I have not implemented it myself, but I am sure it is a good start to switching the buttons on a custom keyboard as of now. Hopefully someone will answer this question on how to incorporate the page-control element.

Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM