DISEÑO DE APLICACIONES: OPCIONES DE...
Transcript of DISEÑO DE APLICACIONES: OPCIONES DE...
DISEÑO DE APLICACIONES: OPCIONES DE NAVEGACIÓN
7 - Junio
Ana C. Murillo
Monday, June 7, 2010
PROGRAMA ESTA SEMANA• Trabajo/evaluación del curso
• Repaso/refuerzo de conceptos de diseño de aplicaciones (vistas, navegación,...)
• Introducción a los sensores del iPhone y las posibilidades que ofrecen
• Presentación de empresa colaboradora: desarrollo sobre Android (Miercoles dia 9).
•Más ejemplos y “demos” con los sensores
• Aplicaciones web ó computer vision en el iPhone con openCV
Monday, June 7, 2010
EVALUACIÓN DEL CURSODiseño de una aplicación “original” (durante la última semana de curso)
• A lo largo de esta semana iremos comentando ideas para el trabajo
• Preparar un párrafo con la descripción de la aplicación a realizar para el lunes 14 de junio (en clase lo comentaremos con cada uno para decidir si el alcance del proyecto es adecuado a cada alumno)
• Presentación de la aplicación: LUNES 21 JUNIO (si no vais a poder asistir ese dia, se pueden realizar presentaciones “adelantadas” el viernes 18 de junio).
Monday, June 7, 2010
ÍNDICE DE HOY
• Repaso de diseño de aplicaciones (navegación, vistas, tablas,...)
• Pintar por pantalla
• Como trasferir al dispositivo
• IDEAS PARA PROFUNDIZAR (en el trabajo):
• Integrar con C/C++
• Instruments (memory leaks, uso/ocupación de memoria, “bottle necks”...)
Monday, June 7, 2010
CONTROL DE NAVEGACIÓN: “NAVIGATION CONTROLERS”
Barra de navegación:UINavigationController
Barra de “tabs”:UITabBarController
Híbrido ...
Monday, June 7, 2010
Pila de vistas: UINavigationController
• Título del controlador de la vista encima de la pila.
• Título del controlador de la vista anterior
• Vista encima de la pila
• Barra de herramientas de la vista encima de la pila
How It Fits Together
6Thursday, January 28, 2010
UINavigationController• Stack of view controllers• Navigation bar
View Controller
View Controller
View Controller
NavigationController
5Thursday, January 28, 2010
Monday, June 7, 2010
Pila de vistas: UINavigationController
Personalizar barras de herramientas: UINavigationItem
Todos los controladores de vistas tienen un “navigationItem” para personalizar títulos, botones,... (opciones en UINavigationBar.h), se visualizan cuando ese controlador está en arriba de la pila:
• Edit/done (muy común, pre-definido) self.navigationItem.leftBarButtonItem = self.editButtonItem;
• Botones a izq. y dcha. : definir un botón y asignarlo como navigation item de la vista actual self.navigationItem.leftBarButtonItem = fooButton; self.navigationItem.rightBarButtonItem = addButton;
• Cambiar el título por algún “control”: self.navigationItem.titleView = segmentedControl;
• Botón de “volver”: por defecto escribe el título de la vista anterior. Se puede cambiar self.title = @“Hello there, CS193P!”; UIBarButtonItem *heyButton = [[UIBarButtonItem alloc] initWithTitle:@“Hey!” . . .]; self.navigationItem.backButtonItem = heyButton;
Navigation Item Ownership
View Controller
Right Bar Button Item
Navigation Item
Left Bar Button Item
Title View
22Thursday, January 28, 2010
Monday, June 7, 2010
en "MyAppDelegate.h"
#import "FirstViewController.h"
...
- (void)applicationDidFinishLaunching:(UIApplication *)application { // INICIALIZAR
navigationController = [[UINavigationController alloc] init]; [window addSubview:navigationController.view]; FirstViewController *viewController =
[[FirstViewController alloc] initWithNibName:@"FirstView" bundle:nil];
[navigationController pushViewController:viewController animated:NO];
[viewController release]; // Override point for customization
after application launch [window makeKeyAndVisible];}
Pila de vistas: UINavigationController
Monday, June 7, 2010
En FirstViewController.m
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization self.title = @"¡Numero Uno!"; } return self;}
- (void)viewDidLoad { [super viewDidLoad];
// AÑADIR BOTONES DE CONTROL UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)]; self.navigationItem.rightBarButtonItem = barButtonItem; [barButtonItem release]; UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"back" style:UIBarButtonItemStyleBordered target:nil action:nil]; self.navigationItem.backBarButtonItem = backBarButtonItem; [backBarButtonItem release];}
- (void)add:(id)sender{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Nothing to add" message:@"Sorry, try again!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; [alertView release];}
Pila de vistas: UINavigationController
Monday, June 7, 2010
en FirstViewController.m
- (IBAction)push:(id)sender{ SecondViewController *secondViewController = [[SecondViewController alloc] initWithText:@"Something"]; [self.navigationController pushViewController:secondViewController animated:YES]; [secondViewController release];}
en SecondViewController.m
- (id)initWithText:(NSString *)someText{ if (self = [self initWithNibName:@"SecondView"
bundle:nil]) {
// Custom initialization self.title = @"Second"; self.text = someText; } return self;}
Pila de vistas: UINavigationController
Monday, June 7, 2010
Pila de vistas: UINavigationController
DEMO: push-pop
Monday, June 7, 2010
Vector de vistas: UITabBarController
• Controlador de la vista seleccionada
• Iconos/nombres de todos los controladores de vistas
UITabBarController• Array of view controllers• Tab bar
View Controller
View Controller
View Controller
Tab BarController
32Thursday, January 28, 2010
How It Fits Together• Selected view controller’s view• All view controllers’ titles
33Thursday, January 28, 2010
Monday, June 7, 2010
- (void)applicationDidFinishLaunching:(UIApplication *)application {
tabBarController = [[UITabBarController alloc] init];
// Create a few view controllers UIViewController *redViewController = [[UIViewController alloc] init]; redViewController.title = @"Red"; redViewController.tabBarItem.image = [UIImage imageNamed:@"faves.png"]; redViewController.view.backgroundColor = [UIColor redColor];
UIViewController *blueViewController = [[UIViewController alloc] init]; blueViewController.title = @"Blue"; blueViewController.tabBarItem.image = [UIImage imageNamed:@"search.png"]; blueViewController.view.backgroundColor = [UIColor blueColor]; MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:nil]; // Add them as children of the tab bar controller tabBarController.viewControllers = [NSArray arrayWithObjects:redViewController, blueViewController, myViewController, nil];
// Don't forget memory management [redViewController release]; [blueViewController release]; [myViewController release]; // Add the tab bar controller's view to the window [window addSubview:tabBarController.view]; [window makeKeyAndVisible];}
Vector de vistas: UITabBarController
Monday, June 7, 2010
Vector de vistas: UITabBarController
Si añadimos muchos elementos al vector, añade automaticamente botón de “more ...” para:
• visualizar el resto y acceder
• configurar el orden
More View Controllers• What happens when a tab bar controller has too many
view controllers to display at once?■ “More” tab bar item
displayed automatically
39Thursday, January 28, 2010Monday, June 7, 2010
Vector de vistas: UITabBarController
DEMO: MyTab
Monday, June 7, 2010
UITabBarController + UINavigationController
Muy común combinarlosTab Bar + Navigation Controllers
Navigation Controller
View Controller
Navigation Controller
View Controller
View ControllerTab Bar Controller
42Thursday, January 28, 2010
...
SimpleFirstController *thirdNavView = [[SimpleFirstController alloc] init];! thirdNavView.title=@"Alumnos";!! UINavigationController *navigationController3=[[UINavigationController alloc] init];! [navigationController3 pushViewController:thirdNavView animated:NO];!! [thirdNavView release];!! NSArray *controllerArray =[[NSArray alloc] initWithObjects:navigationController1,navigationController2,navigationController3, nil];! !! [tabController setViewControllers:controllerArray];...
Monday, June 7, 2010
VISTAS PERSONALIZADAS
• Vista: área rectangular de la pantalla
•Dibuja y/o maneja eventos en esa zona
• Jerarquía de vistas:
• Una superview: - (UIView *)superview
• Varias (o ninguna) subviews: - (NSArray *)subviews
(el orden importa... transparencias!)
Monday, June 7, 2010
VISTAS PERSONALIZADASNormalmente con I.Builder, pero a veces es necesario diseñar vista “manual”: dibujo personalizado y/o manejar eventos (siguiente clase).
• Superposición entre vistas: se ve la que está más arriba
• Podemos utilizar transparencias para ver las sub-vistas de abajo:
• Al dibujar (siguiente...), transparencia por defecto es: opaco 100%.
• Para ocultar una vista del todo: hidden property= YES
Monday, June 7, 2010
DIBUJAR EN PANTALLAAccedemos a los “pixels” de la pantalla que queremos pintar
• Coordenadas en pantalla:
• CGFloat (un float “normal”, usar siempre este tipo para graficos)
• CGPoint (struct de C con dos CGFloats: x,y. Se crea con CGPointMake(x, y) )
• CGSize (struct de C con dos CGFloats: width and height. Se crea con CGSizeMake(width, height)
• CGRect (struct de C con un CGPoint origin y un CGSize size. Se crea con CGRectMake(x, y, width, height)
Monday, June 7, 2010
DIBUJAR EN PANTALLA• Bounds (local): alto y largo de la
vista. Se usa cuando se está implementando una vista
• Frame y center (global): rectángulo que contiene a la vista. Centro relativo a la super-view. Se usa para posicionar la vista dentro de su “superview”.
Origen: arriba a la izquierda!!
Frame >= bounds (rotaciones)
View A
View B
300, 225 2002500, 0
320
320
140, 65
View B’s bounds is ((0,0),(200,250))View B’s frame is ((140,65),(320,320))View B’s center is (300, 225)
Monday, April 12, 2010
View B bounds: ((0,0),(200,250))
View B frame: ((140,65),(320,320))
View B center: (300, 225)
Monday, June 7, 2010
• Subclase de UIView: implementar el método drawRect.
- (void)drawRect:(CGRect)clipRect;
se puede optimizar, no es necesario, no dibujando lo que hay fuera de clipRect
• NUNCA!! llamar directamente a drawRect: avisar que la vista no está actualizada y necesita “redibujar”: drawRect será llamado en el momento adecuado.
- (void)setNeedsDisplay ó - (void)setNeedsDisplayInRect:(CGRect)clipRect
DIBUJAR EN PANTALLA
Monday, June 7, 2010
•Contexto del dibujo: • Determina dónde va el dibujo (pantalla, pdf,...)
• Sólo dura una ejecución de drawRect (nunca almacenar)
• Se obtiene el contexto actual:
- (CGContextRef)UIGraphicsGetCurrentContext();
CGContextRef context = UIGraphicsGetCurrentContext();
• Estilo del dibujo. Se pueden configurar múltiples opciones (fuente, color, tamaño,...): CGContextSetLineWidth(context, 1.0);
DIBUJAR EN PANTALLA
Monday, June 7, 2010
• Path a dibujar : • Empezar el path: CGContextBeginPath(context);
• Mover el “lápiz”, haciendo rectas y arcos:
CGContextMoveToPoint(context, 75, 10); CGContextAddLineToPoint(context, 10, 150); ...
• Cerrar el path: CGContextClosePath(context);
• Establecer propiedades y dibujar el path: [[UIColor greenColor] setFill];
[[UIColor redColor] setStroke]; CGContextDrawPath(context, kCGPathFillStroke);
• Se puede almacenar un path para reutilizarlo, usando CGPath en lugar de CGContext
DIBUJAR EN PANTALLA
Monday, June 7, 2010
DEMO: happy
DIBUJAR EN PANTALLA
Monday, June 7, 2010
MODEL-VIEW-CONTROLER• RECORDAR: Flujo de información a través de los
controladores
Monday, June 7, 2010
DEMO “psicologyst”
Monday, June 7, 2010
PARA TRASFERIR
• Una vez que todo esta “bien” configurado...
developer portal
• Sólo un “click”
Monday, June 7, 2010
VISTAS CON TABLAS Y “SCROLL”
Vistas más flexibles: UIScrollView
• Para mostrar más cosas de las que caben en la pantalla
• Soporta eventos de zoom y de “scroll”
• Subclases: UITableView and UITextView
ContentOffset
15Saturday, January 30, 2010
Monday, June 7, 2010
VISTAS CON TABLAS Y “SCROLL”UITableView: mostrar listas de contenido (1columna, varias filas) permitiendo “scroll” vertical
Table Cell
Table Footer
Table Header
Section Footer
Section
Table Cell
Table Footer
Table Header
Section Footer
Section
UITableViewStylePlain UITableViewStyleGrouped
Cabecera tabla Cabecera tabla
Pie tabla
Pie tabla
Cabecera sección Cabecera sección
Pie secciónPie sección
SecciónSección
CeldaCelda
Monday, June 7, 2010
VISTAS CON TABLAS Y “SCROLL”Solución simple Solución más eficiente
Utilizar un vector para pasar los datos a mostrar
[myTableView setList:myListOfStuff];
Pero!! Se cargan todos los datos al principio y se quedan en memoria
Otro objeto (datasource: UITableViewController) pasa los datos a la tabla (como un “delegate”). Los datos se cargan conforme hacen falta!
Datasource Message Flow
Datasource
41Saturday, January 30, 2010
Cuantas secciones visibles?Qué mostrar en celda de sección 1?
5John Appleseed
Monday, June 7, 2010
VISTAS CON TABLAS Y “SCROLL”Muchas opciones de configuración en UITableView
• Re-utilizar celdas
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@“MyIdentifier”];if (cell == nil) { cell = [[[UITableViewCell alloc]initWithStyle:... reuseIdentifier:@“MyIdenifier”] autorelease]; }
• Cargar datos bajo demanda: cuando una fila se hace visible (automático) o cuando se llama explicitamente “reloadData”
- (void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[self.tableView reloadData];
}
Monday, June 7, 2010
VISTAS CON TABLAS Y “SCROLL”Muchas opciones de configuración en UITableView
• Apariencia de filas y celdas: estilos de celda(UITableViewCellStyleDefault,...), otros “accesorios” (UITableViewCellAccessoryType)
• Responder a eventos de selección: didSelectRowAtIndexPath:(NSIndexPath *)indexPath; willSelectRowAtIndexPath (NSIndexPath *)indexPath
El UITableViewController
• Crea automáticamente un Table view, es su “delegate” y “datasource”.
• Se ocupa de acciones por defecto: reloadData al princripio, de-selecciona filas al navegar hacia atrás, ...
Monday, June 7, 2010