How Swift technology uses Swift to design a custom input method under iOS 8 (mainly used by Nslayoutconstraint)

Source: Internet
Author: User

Current position: > Swift Beginner >

How Swift technology uses Swift to design a custom input method under iOS 8Time:2014-09-10 16:49Source:UnknownAuthor:Ah Cheng ReportClick:562 plays

I will review the contents of the keyboard extension and then design a Morse code input method by using the new app extension API in iOS 8. It takes about 20 minutes to complete this tutorial. Full code

Overview

By replacing the system input method with a custom input method, users can implement some special functions. For example, a particularly novel input method, or input language that is not supported by iOS native. The basic functionality of a custom input method is simple: by tapping, gestures, or other input events, and then inserting text through an unclassified NSString object at the text insertion point of the current text input object.

When the user selects an input method, it becomes the default input method when the app is opened. Therefore, any input method should allow the user to switch to another input method.

For each custom input method, there are two very important points:
1, trust: Your custom Input method allows you to access all the content entered by the user, so the trust between you and your users is very important.
2, a "Next Input Method" option: Compatibility allows the user to switch to another input method must be part of each custom IME interface. You have to provide it in your interface.

Custom input methods are not possible.

There are some input objects that a custom input method cannot use: A secure field (such as a password), a phone number object (like a number field in a contact app).

Your custom Input method cannot access the view level of the input box, nor does it control the cursor and select text.

Similarly, custom input methods cannot display anything outside the top row (just like the system keyboard when you press and hold a key on a subsequent line).

Sand box

By default, a custom IME does not have network access and cannot share files with the app that holds it. If you want to implement these features, you must requestopenaccess the Boolean value to Yes in the Info.plist file. After doing this, the sandbox for custom input methods will be extended, just as it was mentioned in establishing and maintaining user trusts.

If you do need to apply for access, your input method will have the following permissions, each of which will have the corresponding responsibility:

    • Access location Services and address this database, each of which needs to be authorized on the first visit.
    • You can select a shared container with the app that holds the input method, making it possible to customize the glossary in your app.
    • Ability to upload input characters and other input events to the server for processing.
    • Access to icloud, for example, ensures that the input method settings and your auto-correction vocabulary can be synced across all user devices.
    • Access to Game center and in-app purchases with apps that also include input methods.
    • Ability to collaborate with controlled applications if you use to design the keyboard to support mobile device management (MDM)
Top level Design

The next graphic shows what important elements are in the input method under operation, and shows their location in a typical development process. In most cases, we use an application to accommodate this input method extension, a Uiinputviewcontroller to control the keyboard and give feedback on user events.

The custom Input method template contains a subclass of Uiinputviewcontroller, which is the main view controller for your input method. Let's take a look at his interface to get acquainted with how it's implemented:


Class Uiinputviewcontroller:uiviewcontroller, Uitextinputdelegate, Nsobjectprotocol {var inputview:uiinputview! var t extdocumentproxy:nsobject! {Get} func Dismisskeyboard () func advancetonextinputmode ()//This would not provide a complete repository of a language ' s vocabulary.//It is solely intended to supplement existing Lexicons.func requestsupplementarylexiconwithcompletion ( Completionhandler: ((uilexicon!)-> Void)!)}

    • Uiinputviewcontroller supports Uitextinputdelegate protocol, when the text area or text option area changes, through Selectionwillchange,selectiondidchange, Textwillchange and Textdidchange events to achieve.
Design a Morse code input method

We will design and implement a simple input method that can input points and strokes, change the keyboard structure, delete characters and then hide themselves. This example generates the user interface through code. Of course, we can also use the nib file to generate the interface-this will be covered at the end of the tutorial. Loading the nib file can have a negative impact on performance.

Create a project

Open Xcode6, create a single page application, and select Swift as the programming language.

Add a text area

Open Main.storyboard and drag a text area from the component library. We'll use this to test the keyboard we've designed.

Center the text area, and then add the necessary contraints.

Hint: If you call Textfield.becomefirstresponder () in Viewdidload, the keyboard will automatically pop up when the app is opened.

Add this keyboard extension

Select the project file from the Navigator and add a new target by pressing the + button.

Select application extension and then use the custom keyboard template to name it morsecodekeyboard.

This creates a new folder named Morsecodekeyboard, including 2 files Keyboardviewcontroller.swift and info.plist.

Next

Open Keyboardviewcontroller.swift, in order to switch between different keyboards, this keyboard template file will have a button. In the Viewdidload method, put a new method named Addnextkeyboardbutton.

Func Addnextkeyboardbutton () {Self.nextkeyboardbutton = Uibutton.buttonwithtype (. System) as UIButton ... var nextkeyboardbuttonbottomconstraint = Nslayoutconstraint (Item:self.nextKeyboardButton, attribute:. Bottom, Relatedby:. Equal, ToItem:self.view, attribute:. Bottom, multiplier:1.0, constant: -10.0) self.view.addConstraints ([Nextkeyboardbuttonleftsideconstraint, Nextkeyboardbuttonbottomconstraint])}

To better comb the structure of the code, create a new method named Addkeyboardbuttons, and then call it in Viewdidload. Although there are only a few buttons here, there will be more buttons in the real project. Call Addnextkeyboardbutton in Addkeyboardbuttons.

Class Keyboardviewcontroller:uiinputviewcontroller {... override func Viewdidload () {super.viewdidload () addkeyb Oardbuttons ()} func addkeyboardbuttons () {Addnextkeyboardbutton ()} ...}

Point

Now let's add the point button to create a Dotbutton property of type uibutton!.

Class Keyboardviewcontroller:uiinputviewcontroller {var Nextkeyboardbutton:uibutton!var dotbutton:uibutton! ...}

Add a method named Adddot. Use the System button to initialize an attribute that is an alias of Dotbutton. Add a Touchupinside event callback function. Set a large font and then increase the fillet, while increasing the constraint to limit it to 50 points from the horizontal center, vertically centered. This code should be similar to the Nextkeyboardbutton section below.

Func Adddot () {//Initialize the Buttondotbutton = Uibutton.buttonwithtype (. System) as Uibuttondotbutton.settitle (".", Forstate:. Normal) Dotbutton.sizetofit () dotbutton.settranslatesautoresizingmaskintoconstraints (false)  //adding a Callbackdotbutton.addtarget (Self, Action: "Didtapdot", forControlEvents:. Touchupinside)  //make the font biggerdotButton.titleLabel.font = uifont.systemfontofsize (+)  //add rounded Cornersdotbutton.backgroundcolor = Uicolor (white:0.9, alpha:1) DotButton.layer.cornerRadius = 5 view.addsubview (Dotbutton)  //makes the vertical centers Equa;var Dotcenteryconstraint = Nslayoutconstraint (Item:dotbutton, attribute:. CenterY, Relatedby:. Equal, Toitem:view, attribute:. CenterY, multiplier:1.0, constant:0)  //set the button points to the left (-) of the horizontal Centervar Dotcen Terxconstraint = Nslayoutconstraint (Item:dotbutton, attribute:. CenterX, Relatedby:. Equal, Toitem:view, attribute:. CenterX, multiplier:1.0, constAnt: -50)  view.addconstraints ([Dotcenterxconstraint, Dotcenteryconstraint])}

Implement the Dotbutton callback function by using Textdocumentproxy.

Func Didtapdot () {var proxy = Textdocumentproxy as Uitextdocumentproxy proxy.inserttext (".")}

Call the Adddot method in Addkeyboardbuttons.

Func addkeyboardbuttons () {Adddot () Addnextkeyboardbutton ()}

Next to Dash,delete and Hidekeyboard, the process is much more similar. This deletebutton will use the Deletebackward method from proxy, and Hidekeyboardbutton will use the Dismisskeyboard method through Keyboardviewcontroller.

Canoeing

The code associated with dash is almost identical to the Dotbutton code. To make the Dashbutton button symmetrical in the horizontal and the point buttons, simply change the symbol in the horizontal constraint.

Func Adddash () {...//Set the button points to the left (-) of the horizontal Centervar Dotcenterxconstraint = nslayou Tconstraint (Item:dotbutton, attribute:. CenterX, Relatedby:. Equal, Toitem:view, attribute:. CenterX, multiplier:1.0, constant: -50) view.addconstraints ([Dashcenterxconstraint, Dashcenteryconstraint])}

Func Didtapdash () {var proxy = Textdocumentproxy as Uitextdocumentproxy proxy.inserttext ("_")}

Back to delete

When pressed, this delete button will delete the character using the Textdocumentproxy and Deletebackword. This layout constraint will be symmetric with Nextkeyboardbutton (. Left. Right,. Bottom->. TOP)

Func Adddelete () {DeleteButton = Uibutton.buttonwithtype (. System) as Uibuttondeletebutton.settitle ("Delete", Forstate:. Normal) Deletebutton.sizetofit () Deletebutton.settranslatesautoresizingmaskintoconstraints (false) Deletebutton.addtarget (Self, Action: "Didtapdelete", forControlEvents:. Touchupinside) Deletebutton.backgroundcolor = Uicolor (white:0.9, alpha:1) DeleteButton.layer.cornerRadius = 5 View.addsubview (DeleteButton) var rightsideconstraint = Nslayoutconstraint (Item:deletebutton, attribute:. Right, Relatedby:. Equal, Toitem:view, attribute:. Right, multiplier:1.0, constant: -10.0) var topconstraint = Nslayoutconstraint (Item:deletebutton, attribute:. Top, Relatedby:. Equal, Toitem:view, attribute:. Top, multiplier:1.0, constant: +10.0) view.addconstraints ([Rightsideconstraint, Topconstraint])}

Func Didtapdelete () {var proxy = Textdocumentproxy as Uitextdocumentproxy proxy.deletebackward ()}

Hide keyboard

When pressed, the Hidekeyboardbutton will be raised in Keyboardviewcontroller with Dismisskeyboard.

Func Addhidekeyboardbutton () {Hidekeyboardbutton = Uibutton.buttonwithtype (. System) as UIButton hidekeyboardbutton.settitle ("Hide Keyboard", forstate:. Normal) Hidekeyboardbutton.sizetofit () Hidekeyboardbutton.settranslatesautoresizingmaskintoconstraints (false) Hidekeyboardbutton.addtarget (Self, Action: "Dismisskeyboard", forControlEvents:. Touchupinside) View.addsubview (Hidekeyboardbutton) var rightsideconstraint = Nslayoutconstraint (item: Hidekeyboardbutton, attribute:. Right, Relatedby:. Equal, Toitem:view, attribute:. Right, multiplier:1.0, constant: -10.0) var bottomconstraint = Nslayoutconstraint (Item:hidekeyboardbutton, attribute:. Bottom, Relatedby:. Equal, Toitem:view, attribute:. Bottom, multiplier:1.0, constant: -10.0) view.addconstraints ([Rightsideconstraint, Bottomconstraint])}

Using the nib file

If the write constraint isn't the way you're good at it, you can create an interface file and add it to your inputview.

Create an interface file

Right-click the Morsecodekeyboard filegroup and select Create new file.

Select User Interface, and then view Template, named Customkeyboardinterface.

Select File ' Owner, and then under the Identity Inspector tab, change the name of the class to Keyboardviewcontroller.

Add a button to the view and set the title to We? Swift. This interface should look something like this:

Loading interface

Inside the init (Nibname, bundle) constructor, load the Customkeyboard file and save a reference to the interface.

Class Keyboardviewcontroller:uiinputviewcontroller {... var custominterface:uiview! init (Nibname nibnameornil:string ?, bundle Nibbundleornil:nsbundle?) {Super.init (Nibname:nibnameornil, bundle:nibbundleornil) var nib = uinib (nibname: "Customkeyboardinterface", bun Dle:nil) Let objects = Nib.instantiatewithowner (self, options:nil) Custominterface = Objects[0] as UIView} ...}

Add it to Inputview

In the Viewdidload method, add this custom interface to the Inputview.

Class Keyboardviewcontroller:uiinputviewcontroller {... override func Viewdidload () {super.viewdidload () view.ad Dsubview (custominterface) ...} ... }

Add a callback function to a button

Class Keyboardviewcontroller:uiinputviewcontroller {... @IBAction func didtapweheartswift () {var proxy = Textdocumen Tproxy as Uitextdocumentproxy proxy.inserttext ("We? Swift ")} ...}

Bind a button event to a callback function

Right-click on the button, and then tap and drag the Touchupinse event to Didtapweheartswift ibaction.

Finally, this code should be similar to this one.

Install the app on your device

Run your project on the device. He will add a custom keyboard on your device, but before you use it, you must install it.

Go to Settings > general. Select the keyboard-should be at the bottom of the options.

Select the keyboard.

Select Add New Keyboard. Then you will see the Morsecode keyboard, select and then install the keyboard.

Now we can run the app again and then use your keyboard.

How Swift technology uses Swift to design a custom input method under iOS 8 (mainly used by Nslayoutconstraint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.