How to make a Native App Form that doesn't suck with Titanium
Some things are much more difficult to do in a native app than on the web. But forms are not one of them. Both iOS and Android give us simple tools to make form interaction nice and easy.
Unfortunately the Titanium docs make it almost impossible to figure out. Don't get me wrong, the docs are great, and the Kitchen Sink app they supply covers 80% of the things you can do. But making a nice form was somehow left off.
In particular, I was looking to make a form with sections that are stacked together, had a hint and no label, and led you from field to field. After tons of searching docs, Q&A and googling, I did it.
I'll show you the code first and then go through it.
This is in a file I called login.js that is called by a window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
var window = Ti.UI.currentWindow; var loginField = Ti.UI.createTextField({ value:'', width:300, height: 40, left: 5, hintText: 'Username', returnKeyType:Titanium.UI.RETURNKEY_NEXT, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE }); var passwordField = Ti.UI.createTextField({ value:'', height: 40, passwordMask: true, hintText: 'Password', width:300, left: 5, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE, returnKeyType:Titanium.UI.RETURNKEY_DONE }); loginField.addEventListener('return', function(event) { passwordField.focus(); }); passwordField.addEventListener('return', function(event) { // submit your form here }); var table = Ti.UI.createTableView({ style: Ti.UI.iPhone.TableViewStyle.GROUPED, rowHeight: 40 }); var section = Ti.UI.createTableViewSection({headerTitle: "Sign in"}); var row = Ti.UI.createTableViewRow(); row.add(loginField); row.hasChild = false; row.className = "field"; section.add(row); var prow = Ti.UI.createTableViewRow(); prow.add(passwordField); prow.hasChild = false; prow.className = "field"; section.add(prow); table.setData([section]); window.add(table); |
It's pretty simple really.
The first part creates a username and password field. The key parts here are:
1 2 3 |
hintText: "Username", returnKeyType:Titanium.UI.RETURNKEY_NEXT, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE |
- hintText adds the helper text so you don't need a label.
- returnKeyType basically changes the text on the input keyboard return key.
- borderStyle we set to none so that we can let the table view handle the borders.
In the next part we set event listeners for when that return key is pressed. We can auto forward the user to the next field using .focus();
Next we create a table that is GROUPED, add our inputs to simple rows and put them in the table. Make sure the row height is the same as the input height so that the rows appear to be the inputs.
Here's the result: