10 trucos útiles y fragmentos para Apple iPhone y Xcode

1. Cadenas en varias líneas

En Xcode, se puede "romper" una cadena en varias líneas mediante la inserción en el extremo de una barra invertida "\". Esta característica puede ser útil cuando, por ejemplo, queremos insertar el texto HTML en un control UIWebView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
htmlData = @ " \ NSString * HTMLData @ = "\
<html> <head> \
<style type= \" text/css \"> \
body {background: # 000; color: # fff} \
</ Style> \
<title> informe </ title> </ head> \
<body> \
Trate de <h1> HTML </ h1> \
<ul> \
<li> texto HTML </ li> \
Enviado el <li> </ li> \
<li> más líneas "</ li> \
</ Ul> </ body> </ html> ";
htmlData baseURL : [ NSURL URLWithString : @ "http://www.saidmade.com/" ] ] ; [WebView loadHTMLString: HTMLData URL base: [ NSURL URLWithString: @ "http://www.saidmade.com/"]];

2. Las transiciones entre Vista con efecto "papel doblado"

Esta es una característica muy útil para navegar y risflogliare, dos UIView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/ / Realiza una transición a partir del CURL a un UIView UIView
/ / @ Parámetros marcador de posición (UIView) principal
/ / @ Params fview (UIView) de salida
/ / @ Params TView (UIView) llegada
/ / @ Params adelante (BOOL) navegar hacia arriba o abajo

void ) makeTansitionFromView : ( UIWindow * ) placeholder fromView : ( UIView * ) fview toView : ( UIView * ) tview forward : ( BOOL ) forward { - (Void) makeTansitionFromView: (UIWindow *) fromView marcador de posición: (* UIView) fview toView: (* UIView) TView adelante: (BOOL) {adelante
nil context : NULL ] ; [BeginAnimations UIView: contexto nada: NULL];
1.5 ] ; [UIView setAnimationDuration: 1,5];
forward?UIViewAnimationTransitionCurlUp : UIViewAnimationTransitionCurlDown forView : placeholder cache : YES ] ; [UIView setAnimationTransition: adelante UIViewAnimationTransitionCurlUp: UIViewAnimationTransitionCurlDown forView: caché de marcador de posición: YES];
; [TView removeFromSuperview];
fview ] ; [Placeholder addSubview: fview];
; [Fview removeFromSuperview];
tview ] ; [Placeholder addSubview: TView];
; [CommitAnimations UIView];
}

Puede ser utilizado de esta manera:

1
2
3
4
/ / Mostrar - Avanzar
window fromView : primaView.view toView : secondaView.view forward : YES ] ; [Self makeTansitionFromView: ventana fromView: primaView.view toView: secondaView.view adelante: YES];
/ / Ocultar - hojear de nuevo
window fromView : secondaView.view toView : primaView.view forward : NO ] ; [Self makeTansitionFromView: ventana fromView: secondaView.view toView: primaView.view adelante: NO],

3. Prevenir con atenuación automática de la pantalla

Para ser utilizado con cuidado, so pena de consumo inmediato de la batería, esta línea de código hace que sea posible para mantener nuestra aplicación siempre visible, evitando que el iPhone de Apple entra en "standby"

1
.idleTimerDisabled = YES ; [SharedApplication UIApplication] IdleTimerDisabled = YES.;

4. Indicador de actividad de la red

La animación que aparece en la barra de estado en la parte superior de la pantalla del iPhone de Apple también se puede utilizar para resaltar una aplicación en nuestra red:

1
2
3
4
5
6
7
/ Red / Mostrar indicador de actividad ...
.networkActivityIndicatorVisible = YES ; [SharedApplication UIApplication] NetworkActivityIndicatorVisible = YES.;

/ / Sus operaciones ...

/ / Ocultar indicador de actividad de red ...
.networkActivityIndicatorVisible = NO ; [SharedApplication UIApplication] NetworkActivityIndicatorVisible = NO.;

5. Indicador de actividad personal

Si usted no tiene la barra de estado, puede ser útil para mostrar un indicador de nuestra actividad:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/ / Foro Ambiental Mundial en algún lugar ... Edipo en un delegado (. H)
* UIActivityIndicatorView actividad;

/ / Inicializar el viewDidLoad En loadView o Indicador de Actividad
UIActivityIndicatorView alloc ] initWithActivityIndicatorStyle : UIActivityIndicatorViewStyleWhite ] ; actividad = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
activity ] ; [Self.view addSubview: la actividad];
CGPointMake ( 160 , 240 ) ] ; [Actividad setCenter: CGPointMake (160, 240)];
; [Actividad StopAnimating];

/ / Cuando es necesario
void ) someMethod { - (Void) {algunMetodo
; [Actividad StartAnimating];
/ / Para hacer ...
; [Actividad StopAnimating];
}

6. Ubicación

Con este fragmento se puede entender que "el lenguaje" está en nuestro dispositivo:

1
2
3
4
5
6
7
/ / Comprobación de la lengua y la localización
defaults = [ NSUserDefaults standardUserDefaults ] ; NSUserDefaults * por defecto = [ NSUserDefaults standardUserDefaults];
languages = [ defaults objectForKey : @ "AppleLanguages" ] ; NSArray idiomas * = [defaults objectForKey: @ "espanol.applelanguages"];
currentLanguage = [ languages objectAtIndex : 0 ] ; NSString * currentLanguage = [idiomas objectAtIndex: 0];

"Current Locale: %@" , [ [ NSLocale currentLocale ] localeIdentifier ] ) ; NSLog (@ "localización actual:% @", [[ NSLocale currentLocale] LocaleIdentifier]);
"Current language: %@" , currentLanguage ) ; NSLog (@ "Idioma actual:% @", currentLanguage);

7. iPhone o iPod?

Esta clase es útil para determinar qué dispositivo de Apple se está ejecutando nuestra aplicación. No sólo podemos determinar el modelo (iPhone o iPod Touch), sino también la versión. : Crea dos archivos UIDevice-hardware.h y UIDevice-hardware.m :

1
2
3
4
5
6
7
8
9
10
11
12
13
/ / UIDevice-hardware.h
# Importar <UIKit/UIKit.h>

@ # Definir IPHONE_1G_NAMESTRING "iPhone 1G"
@ # Definir IPHONE_3G_NAMESTRING "iPhone 3G"
@ # Definir IPHONE_3GS_NAMESTRING "iPhone 3G"
@ # Definir IPOD_1G_NAMESTRING "iPod touch 1G"
@ # Definir IPOD_2G_NAMESTRING "iPod Touch 2G"

Hardware ) @ Interface UIDevice (Hardware)
NSString * ) platform; - ( NSString *) la plataforma;
NSString * ) platformString; - ( NSString *) platformString;
@ End
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
/ / UIDevice-hardware.m
# Import "UIDevice-hardware.h"
# Include <sys/types.h>
# Incluye <sys/sysctl.h>

Hardware ) @ Implementación UIDevice (Hardware)

/ *
Plataformas
iPhone1, 1 = 1G iPhone
iPhone1, 2 = iPhone 3G
iPhone2, 1 = el iPhone 3G
iPod1, 1 = iPod Touch 1G
iPod2, 1 = iPod touch 2G
* /

NSString * ) platform { - ( NSString *) {plataforma
size_t size;
, NULL , & size, NULL , 0 ) ; sysctlbyname ("hw.machine", NULL, y la talla, NULL, 0);
machine = malloc ( size ) ; char * máquina = malloc (size);
, machine, & size, NULL , 0 ) ; ysctlbyname ("hw.machine", las máquinas, y la talla, NULL, 0);
platform = [ NSString stringWithCString : machine ] ; NSString * plataforma = [ NSString stringWithCString: equipo];
machine ) ; libre (máquina);
cambio de plataforma;
}

NSString * ) platformString { - ( NSString *) {platformString
platform = [ self platform ] ; NSString * plataforma = [plataforma de sí mismo];
platform isEqualToString : @ "iPhone1,1" ] ) return IPHONE_1G_NAMESTRING; if ([plataforma isEqualToString: @ "iPhone1, 1"]) return IPHONE_1G_NAMESTRING;
platform isEqualToString : @ "iPhone1,2" ] ) return IPHONE_3G_NAMESTRING; if ([plataforma isEqualToString: @ "iPhone1, 2"]) return IPHONE_3G_NAMESTRING;
platform isEqualToString : @ "iPhone2,1" ] ) return IPHONE_3GS_NAMESTRING; if ([plataforma isEqualToString: @ "iPhone2, 1"]) return IPHONE_3GS_NAMESTRING;
platform isEqualToString : @ "iPod1,1" ] ) return IPOD_1G_NAMESTRING; if ([plataforma isEqualToString: @ "iPod1, 1"]) return IPOD_1G_NAMESTRING;
platform isEqualToString : @ "iPod2,1" ] ) return IPOD_2G_NAMESTRING; if ([plataforma isEqualToString: @ "iPod2, 1"]) return IPOD_2G_NAMESTRING;
; devuelven NULL;
}
@ End

En nuestra delegación para participar:

1
2
3
4
5
6
# Import "UIDevice-hardware.h"
/ /
void ) checkDeviceTypeAndCapabilities { - (Void) {checkDeviceTypeAndCapabilities
"type: %@" , [ [ UIDevice currentDevice ] platform ] ) ; NSLog (@ ", escriba:% @", [[UIDevice currentDevice] plataforma]);
"type: %@" , [ [ UIDevice currentDevice ] platformString ] ) ; NSLog (@ ", escriba:% @", [[UIDevice currentDevice] platformString]);
}

8. Habitación

Cuando se escribe una aplicación que utiliza el acceso a las funciones de la Cámara es para verificar que el "dispositivo" compatible con estas características (de acuerdo con las directrices de Apple):

1
2
3
4
5
6
* UIImagePickerController imgPicker;
/ / ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypeCamera ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.imgPicker animated : YES ] ; [PresentModalViewController vacaciones: self.imgPicker animados: YES];
}

9. Álbumes de fotos y biblioteca de fotos

Similar a lo que sucede con la Cámara, lo mejor es comprobar sólo cuando se accede a la biblioteca de la imagen:

1
2
3
4
5
6
7
8
9
10
11
* UIImagePickerController imgPicker;
/ / ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypeSavedPhotosAlbum ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
self.imgPicker animated : YES ] ; [PresentModalViewController vacaciones: self.imgPicker animados: YES];
}
/ / O ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypePhotoLibrary ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imgPicker animated : YES ] ; [PresentModalViewController vacaciones: self.imgPicker animados: YES];
}

10. Disponibilidad y tipo de red

Afortunadamente, Apple ha escrito una clase para que podamos determinar el estado de la red. Esto puede ser usado en nuestra aplicación es para comprobar que la topología de la red: Ethernet o WiFi. Descargar Reachability.h y Reachability.m . Agregue el marco SystemConfiguration.framework . Aquí usted puede escribir una función como:

1
2
3
4
5
6
7
8
9
10
/ / En su delegado. H
Accesibilidad @ de clase;
/ /
/ / Los delegados in M
# Import "Reachability.h"

/ / Comprobar la cobertura de la red
BOOL ) CheckNetworkStatus { - (BOOL) {CheckNetworkStatus
Reachability reachabilityForInternetConnection ] retain ] != NotReachable ) ; return ([[reachabilityForInternetConnection Accesibilidad] conservar] NotReachable =!);
}

Tenga en cuenta que el código de Apple, que está disponible en código fuente completo Reachability.zip es para SDK 3.1.2. Si usted trata de reemplazar a SDK 2.2.1 es necesario comentar algunas partes del código no son compatibles con el "viejo" (aunque todavía existen) SDK, como definir:

1
2
kSCNetworkReachabilityFlagsConnectionOnTraffic
kSCNetworkReachabilityFlagsConnectionOnDemand

y la pieza de código (para hacer comentarios):

1
2
3
4
5
6
7
8
9
10
11
12
/ / Si ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) = 0)! | |
/ / (Banderas y kSCNetworkReachabilityFlagsConnectionOnTraffic)! = 0))
/ / {
/ / / / ... y la conexión es a demanda (o en el tráfico), si el
/ / / / Llamar a la aplicación utiliza la API o superior CFSocketStream
/ /
/ / If ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
/ / {
/ / / / ... y no intervención [usuario] es necesario
/ / RetVal = ReachableViaWiFi;
/ /}
/ /}

No hay comentarios para esta entrada

Deja un comentario

XHTML PERMISO TAG: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> código de inserción:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL