Salta al contingut principal

Titanium Mobile: Create a Sliding Menu for iOS

This tutorial will teach you how to build a sliding menu similar to the one featured in the Facebook application using Titanium Mobile.




Step 1: Getting Started


The sliding menu consists of a full-sized window (the main window) on top of a smaller one that contains a table view (the menu). To create the sliding effect, we’ll have to trigger an animation that will track and follow a touch event horizontally. However, let’s save that for later. For now, we’ll start by setting up the windows.


First, we’ll create the menu:



//// ---- Menu window, positioned on the left
var menuWindow = Ti.UI.createWindow({
top:0,
left:0,
width:150
});
menuWindow.open();
//// ---- Menu Table
// Menu Titles
var menuTitles = [
{title: 'Menu 1'},
{title: 'Menu 2'},
{title: 'Menu 3'},
{title: 'Menu 4'},
{title: 'Menu 5'},
{title: 'Menu 6'}
];
// Tableview
var tableView = Ti.UI.createTableView({
data:menuTitles
});
menuWindow.add(tableView);

This is a very basic table view setup, but it will do. So you should now have something like the following:





Step 2: Main Window


Now we need a window with a navigation bar and a button in it that will allow us to open the menu with an animation. So, in order to achieve this, we actually need two windows: one containing a navigationGroup (indispensable in order to have a navigation bar) and another one that is in the navigationGroup:



//// ---- Window with navigationGroup
var navWindow = Ti.UI.createWindow({
width:320 // Set the width of the sliding window to avoid cut out from animation
});
navWindow.open();
// Main window
var win = Ti.UI.createWindow({
title:'Main Window',
backgroundColor:'#28292c',
barColor:'#28292c'
});
// NavigationGroup
var navGroup = Ti.UI.iPhone.createNavigationGroup({
window:win
});
navWindow.add(navGroup);
// Top left button
var menuButton = Ti.UI.createButton({
title:'Menu',
toggle:false // Custom property for menu toggle
});
win.setLeftNavButton(menuButton);

Hey, you probably noticed that toggle:true property in our button, right? It doesn’t really exist; it’s a custom property that I added. You can pretty much name it however you want or even create a variable for it (like var toggle = true;) if it makes you feel more comfortable. However, I recommend you use this little trick because it is really handy when you have a lot of custom properties in your app.


Here is our main window:





Step 3: Toggle Menu


Okay, now we’re going to animate our window so it slides from left to right when we press the “Menu” button.


Let’s see how it works:



menuButton.addEventListener('click', function(e){
// If the menu is opened
if(e.source.toggle == true){
navWindow.animate({
left:0,
duration:400,
curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
});
e.source.toggle = false;
}
// If the menu isn't opened
else{
navWindow.animate({
left:150,
duration:400,
curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
});
e.source.toggle = true;
}
});

You see that when we click the button, we call function(e), where e is our object (the button). By calling e.source.toggle, we are checking the custom “toggle” property discussed above (you can also use menuButton.toggle, it’s the same thing). If it is false, we’re moving our window to the right and switching the property to true. So, of course, if it’s true, the window goes back to normal and our property is then set to false again.


The curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT is just a way to smooth the animation.





Step 4: Tracking


Yeah, this is looking pretty neat, right? But that was the easy part, because now we are getting serious! We’ll track a touch event so that we can reveal the menu by moving the main window horizontally. But before that, we’ll add some custom properties:



// Main window
var win = Ti.UI.createWindow({
title:'Main Window',
backgroundColor:'#28292c',
barColor:'#28292c',
moving:false, // Custom property for movement
axis:0 // Custom property for X axis
});

Again, you can name these properties however you want, or you can even create dedicated variables for them, but I strogly recommend you use this method because it saves memory and it is easier to read than a bunch of variables scattered over your nice file.


Now we’re going to use the touchstart event to get the position of our finger when it touches the screen:



win.addEventListener('touchstart', function(e){
// Get starting horizontal position
e.source.axis = parseInt(e.x);
});

Here we take the horizontal coordinate (e.x) of our event, parse it as an integer, and then save it in our custom property axis.


Next we are going to animate the window depending on the position of our finger:



win.addEventListener('touchmove', function(e){
// Subtracting current position to starting horizontal position
var coordinates = parseInt(e.globalPoint.x) - e.source.axis;
// Detecting movement after a 20px shift
if(coordinates > 20 || coordinates < -20){
e.source.moving = true;
}
// Locks the window so it doesn't move further than allowed
if(e.source.moving == true && coordinates <= 150 && coordinates >= 0){
// This will smooth the animation and make it less jumpy
navWindow.animate({
left:coordinates,
duration:20
});
// Defining coordinates as the final left position
navWindow.left = coordinates;
}
});

To prevent the window from moving everytime we touch it, we are waiting for a movement over 20 pixels before animating. We track our touch coordinate with e.globalPoint.x and subtract it to our starting point (axis) so we can move the window. Also, it can not slide beyond the menu width (150 pixels) or beyond the left side of the screen.




Step 5: Back to Normal


If you try to run your app, you’ll see that your window will stay exactly where you leave it. That’s not what we want. We need to reposition it when the touch event is over, so it will open/close itself depending on where it is:



win.addEventListener('touchend', function(e){
// No longer moving the window
e.source.moving = false;
if(navWindow.left >= 75 && navWindow.left < 150){
// Repositioning the window to the right
navWindow.animate({
left:150,
duration:300
});
menuButton.toggle = true;
}else{
// Repositioning the window to the left
navWindow.animate({
left:0,
duration:300
});
menuButton.toggle = false;
}
});

When our finger no longer touches the screen, the touchend event is fired, so we can adjust the position of our window.




Conclusion


We’re done! As you see, we used a very basic animation and math to achieve a great and professional effect. I really hope you enjoyed this tutorial and learned a few new tricks!







via Mobiletuts+ http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-create-a-sliding-menu-for-ios/

Comentaris

Entrades populars d'aquest blog

15 Tutoriales CSS3 para mejorar tus paginas web

15 Tutoriales CSS3 para mejorar tus paginas web : Les dejo una pequeña recopilación de tutoriales CSS3 que espero sean de utilidad para ustedes, intentamos hacer una recopilación bastante completa para crear impresionantes diseños web con CSS3 y aprovechar las bondades de CSS3 incluso para aplicar efectos, son un total de 15 tutoriales CSS3 gratis . Crear menu dropdown con CSS3 Crear breadcrumbs con estilo Transiciones de paginas con CSS3 Crear timeline con CSS3 y jQuery Reproductor de video con HTML5, CSS3 y jQuery Crear efecto acordion CSS3 Aplicar degradado a texto Crear texto en curva con CSS3 y jQuery Aplicar textura a texto con Magic Pill Crear slider de imagenes con CSS3 y jQuery Rotar texto con CSS3 Crear menu vertical con CSS3 Crear formulario con HTML5 y CSS3 Crear efecto de imagenes apiladas con CSS3 Aplicar estilos para imagenes con CSS3  

Averiguar la Salud del Disco Duro, con Crystal Disk Info [Windows]

Averiguar la Salud del Disco Duro, con Crystal Disk Info [Windows] : El actual “cuello de botella” en nuestras PCs; es decir, donde todo el rendimiento de nuestra PC llega a estancarse , es en el Disco Duro. Si bien los procesadores han evolucionado considerablemente en velocidad / rendimiento, el RAM no sólo es más económico, sino más veloz, y las tarjetas de video siguen innovando con cada generación, los discos duros han permanecido idénticos desde hace años, limitados por la física. Y es que un disco duro tradicional sólo tiene un máximo de velocidad con el que puede girar (medido en revoluciones por minuto, o RPM) que, a su vez, limita la velocidad de lectura y escritura. En pocas palabras, a pesar de que nuestras PCs pueden procesar información mucho más rápido que hace 5 años, los discos duros siguen leyendo (y escribiendo) esta información prácticamente a la misma velocidad. Esto ha cambiado con la llegada de los SSD, los Discos de Estado Sólo que no están limitados por la velo...

Cómo programar add-ons en XBMC: Un add-on más completo

Este tutorial forma parte de la serie Cómo programar un add-on de XBMC Estamos a mitad de camino de este tutorial, pero ya tienes el conocimiento necesario para hacer un add-on bastante completo. Espero que a estas alturas ya te hayas convencido de que es algo relativamente sencillo sin necesidad de saber demasiado de programación. Y ya sabes cómo obtener datos de una página HTML usando expresiones regulares, que es lo más difícil. Así que antes de entrar en la recta final vamos construir un add-on paso a paso desde cero, con el objetivo de afianzar lo que has aprendido en las entregas anteriores y de paso divertirte un poco. Te aconsejo que elijas un sitio web que te guste como fuente de vídeos, para mí he elegido hacer un add-on completo que permita ver los vídeos de Disney Junior tanto en la web oficial como en YouTube. No se trata de un add-on demasiado complejo, como podrás comprobar enseguida, pero no va a desmerecer en nada a cualquiera de los que puedes encontrar publicados en...