Documente Academic
Documente Profesional
Documente Cultură
Dismiss
IOS 8
18 52 2
Starting with iOS 8, your applications can extend custom functionality and content
beyond your app, and make it available to users while they're using other apps or
the operating system. One way of extending the operating system is by creating a
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
custom keyboard.
In this tutorial I'm going to show you how to make your own custom keyboard using
Swift and the new app extension APIs. Before we do that, we are going to go over
what a keyboard extension can do, what it can't do, and what it should to get
approved for the App Store.
1. Overview
A custom keyboard replaces the system keyboard for users who want capabilities,
such as a novel text input method or the ability to enter text in a language not
otherwise supported by the operating system.
After a user chooses a keyboard, it remains as the default one whenever they open
an app. For this reason the keyboard must allow the user to switch to another
keyboard.
If you only need to add a few buttons to the system keyboard, then you should look
into custom views for data input.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Your custom keyboard does not have access to the view hierarchy of the input, it
cannot control the cursor, and is unable to select text. Also, the custom keyboard
cannot display anything above the top row. The system keyboard isn't limited by
these constraints. For example, it shows an extension when you tap a key to show
the user what key was tapped.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
The red line shows the top limit of a custom keyboard.
Sandboxing
By default, a keyboard has no network access and cannot share files with its
containing app. To enable these capabilities, set the value of
the RequestsOpenAccess key in the Info.plist file to YES . Doing so expands the
keyboard's sandbox as described in Apple's App Extension Programming Guide.
If you do request open access, your keyboard gains the following capabilities, each
with a concomitant responsibility:
access to location services and the address book database, each requiring
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
the user's permission on first access
option to use a shared container with the keyboard's containing app, which
enables features, such as providing a custom lexicon management user
interface in the containing app
ability to send keystrokes and other input events for server-side processing
access to iCloud, which you can use, for example, to ensure that keyboard
settings and your custom autocorrect lexicon are up to date on all devices
owned by the user
access to Game Center and in-app purchase through the containing app
ability to work with managed apps if you design your keyboard to support
mobile device management (MDM)
Be sure to read Apple's Designing for User Trust document, which describes your
responsibilities for respecting and protecting user data in case you request open
access.
3. How It Works
In the most basic form we have an application that contains a keyboard extension
and a UIInputViewController that controls the keyboard and responds to user
events.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
The Custom Keyboard template contains a subclass of UIInputViewController,
which is the primary view controller of your keyboard. Let's look at the interface to
get a feel of how it works.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 self.textDocumentProxy.insertText(
"Tuts+") // inserts the string "Tuts+" at the inser
2
3 self.textDocumentProxy.deleteBackward()
// Deletes the character to the left of the i
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 2: Add a Text Field
Open Main.storyboard and drag a text field from the Objects Library. We'll use
this to test the keyboard later. Center the text field and add the necessary layout
constraints as shown below.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
If you call textField.becomeFirstResponder()in viewDidLoad the keyboard will
open when you start the app.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 3: Add the Keyboard Extension
Select the project file in theProject Navigator and add a new target by clicking the
plus button at the bottom.
Select Application Extension on the left, choose the Custom Keyboard template,
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
and name it Calculator.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
This will create a new group namedCalculator, containing two
files KeyboardViewController.swift and Info.plist.
Step 4: Cleaning Up
Open KeyboardViewController.swift. The template keyboard has one button,
letting the user switch between keyboards. Remove the code in
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
the viewDidLoad method.
Open the XIB file and, in the Attributes Inspector on the right, set the size
to Freeform and the status bar to None.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
In the Size Inspector set the width of the view to 320 and the height to 160 .
Drag a button from the Objects Library to the view. In the Attributes Inspector,
set the title to 1. In the Size Inspector, set the button's width and height to
30 . Move the button to the top right corner of the view until it aligns with the
margins.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Copy the button by clicking and dragging the button while pressing theOption key.
Position the second button below the first one.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Select the buttons by pressing Command-A and copy the buttons. Position the new
buttons below the first and second button.
Repeat the process to create another column of buttons until you have four columns
of buttons.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Next, select the column on the left and make a copy that aligns with the left border
of the view.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Set the width of the buttons to 140 points. Replace the top left button with a label
that has the same size as the button. Rename the buttons like in the screenshot
bellow.
Give the view a blueish background color and set the background color for the
buttons to white with an opacity of 15%. And for the display label, make it black with
an opacity of 15%. Set the text size to 18 points for every user interface object and
set the text color to white. The user interface should now look like this:
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 6: Loading the User Interface
We first need to create a property in which to store the user interface.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
01 class KeyboardViewController: UIInputViewController {
02 ...
03
04 override func viewDidLoad() {
05 super.viewDidLoad()
06
07 loadInterface()
08 }
09
10 func loadInterface() {
11 // load the nib file
12 var calculatorNib = UINib(nibName:"Calculator", bundle: nil)
13 // instantiate the view
14 calculatorView = calculatorNib.instantiateWithOwner(self, options: nil)[0]
15
16 // add the interface to the main view
17 view.addSubview(calculatorView)
18
19 // copy the background color
20 view.backgroundColor = calculatorView.backgroundColor
21 }
22
23 ...
24 }
If you are using the iOS Simulator, the custom keyboard might not work inside your
app. To see the keyboard press home and open Spotlight.
Open Calculator.xib , Select File's Owner, and in the Identity Inspector change
its class to KeyboardViewController.
Right click on the Next Keyboard button and connect a referencing outlet to
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
the File's Owner.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
In the loadInterface method, we add an action to the nextKeyboard button as
shown below.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Create a method named clearDisplay and call it in the viewDidLoad method,
after invoking loadInterface. The display should now show 0 when you open the
keyboard.
Create a method named didTapNumber and connect it in Interface Builder to all the
number buttons for the touch up inside event. The method uses the titleLabel
of the button to determine which number was tapped.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Update the clearDisplay method as shown below.
The keyboard code is in a different target than your app. Because of this the debug
logs aren't visible. To see the logs for the Calculator target, open the system log
from the iOS Simulator.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 11: Dot Input
The button to insert a dot should add a dot to the display, but only if there isn't a dot
present yet.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
01 class KeyboardViewController: UIInputViewController {
02 ...
03
04 @IBAction func didTapInsert() {
05 var proxy = textDocumentProxy as UITextDocumentProxy
06
07 if let input = display?.text as String? {
08 proxy.insertText(input)
09 }
10 }
11 }
Let's take a simple input in order to understand how the calculator algorithm works:
Observations:
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
11
12 // apply the operation
13 switch nextOperation {
14 case .Addition:
15 result = internalMemory + inputAsDouble
16 case .Subtraction:
17 result = internalMemory - inputAsDouble
18 case .Multiplication:
19 result = internalMemory * inputAsDouble
20 case .Division:
21 result = internalMemory / inputAsDouble
22 default:
23 result = 0.0
24 }
25
26 nextOperation = Operation.None
27
28 var output = "\(result)"
29
30 // if the result is an integer don't show the decimal point
31 if output.hasSuffix(".0") {
32 output = "\(Int(result))"
33 }
34
35 // truncatingg to last five digits
36 var components = output.componentsSeparatedByString(
".")
37 if components.count >= 2 {
38 var beforePoint = components[0]
39 var afterPoint = components[1]
40 if afterPoint.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 5
41 let index: String.Index = advance(afterPoint.startIndex, 5)
42 afterPoint = afterPoint.substringToIndex(index)
43 }
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
43 }
44 output = beforePoint +"." + afterPoint
45 }
46
47
48 // update the display
49 display.text = output
50
51 // save the result
52 internalMemory = result
53
54 // remember to clear the display before inserting a new number
55 shouldClearDisplayBeforeInserting =true
56 }
57 }
58 }
Update the clearDisplayMethod as shown below. When the user starts to write the
first number, the internal memory should be set to 0 and nextOperation should
be addition. That way, after the user inputs the first number and presses an
operation, the calculator will remember the inputted number.
Advertisement
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
03 didSet {
04 layer.cornerRadius = cornerRadius
05 }
06 }
07 }
08
09 class RoundLabel: UILabel {
10 @IBInspectable var cornerRadius: CGFloat = 0 {
11 didSet {
12 layer.cornerRadius = cornerRadius
13 }
14 }
15 }
In Interface Builder, select the buttons and change their class to RoundButton in the
Identity Inspector. In the Attributes inspector, you should see the new corner
radius attribute.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Do the same for the display label. Your keyboard should now look like this.
Conclusion
You should now be able to make a custom keyboard in iOS using the app extension
APIs. Remember that every custom keyboard must have a way to switch to the next
keyboard and that your keyboard cannot connect to the internet, access location
services, or talk with its containing app by default, but you can request these
capabilities.
The system will use the default keyboard for secure fields, such as password and
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
phone number fields. Don't forget that the code for the custom keyboard lives in a
separate target. Because of this the debug logs aren't visible. To see them, open
the system log from the iOS Simulator.
Advertisement
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
iOS 8 Swift iOS SDK Xcode 6 Xcode
Translations Available:
Tuts+ tutorials are translated by our community Building iOS Apps in C# With Xamarin Start
members. If you'd like to translate this post into
another language, let us know!
Related Tutorials
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
iOS 8: Creating a Today Widget
Code
Jobs
WordPress Developer
at WebDevStudios in Los Angeles, CA,
USA
Advertisement
Front-End WordPress Designer
at WebDevStudios in Los Angeles, CA,
USA
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
0 Comments Tuts+ Hub
Sort by Best
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement
Email Address
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Help and Support Email Address
FAQ
Subscribe
Terms of Use
Contact Support Privacy Policy
About Tuts+
Advertise
Teach at Tuts+
2014 Envato Pty Ltd. Trademarks and brands are the property of their respective
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
owners.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com