10 truques úteis e trechos para Apple iPhone e Xcode

1. Cordas em várias linhas

No Xcode, você pode "quebrar" uma string em várias linhas, inserindo no final com uma barra invertida "\". Este recurso pode ser útil quando, por exemplo, queremos inserir o texto HTML em um controle UIWebView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
htmlData = @ " \ NSString * HTMLData @ = "\
<html> <head> \
<style type= \" text/css \"> \
{background: # 000; color: # fff} corpo \
</ Style> \
Assinalar <title> </ title> </ head> \
<body> \
Tente <h1> HTML </ h1> \
<ul> \
Texto <li> HTML </ li> \
Enviado em <li> </ li> \
linhas "<li> mais </ li> \
</ Ul> </ body> </ html> ";
htmlData baseURL : [ NSURL URLWithString : @ "http://www.saidmade.com/" ] ] ; [WebView loadHTMLString: HTMLData baseURL: [ NSURL URLWithString: @ "http://www.saidmade.com/"]];

2. Transições entre Ver com efeito "dobrado"

Aqui é um recurso útil para navegar e risflogliare, dois UIView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/ / Executa uma transição com efeitos a partir de CURL para um UIView UIView
/ / @ Params espaço reservado (UIView) principal
/ / @ Params fview (UIView) de partida
/ / @ Params TView chegada (UIView)
/ / @ Params para a frente (BOOL) navegar para cima ou para baixo

void ) makeTansitionFromView : ( UIWindow * ) placeholder fromView : ( UIView * ) fview toView : ( UIView * ) tview forward : ( BOOL ) forward { - (Void) makeTansitionFromView: (UIWindow *) espaço reservado fromView: (UIView *) fview toView: (UIView *) TView frente: (BOOL) {frente
nil context : NULL ] ; [UIView beginAnimations: contexto nil: NULL];
1.5 ] ; [UIView setAnimationDuration: 1.5];
forward?UIViewAnimationTransitionCurlUp : UIViewAnimationTransitionCurlDown forView : placeholder cache : YES ] ; [UIView setAnimationTransition: forward UIViewAnimationTransitionCurlUp: UIViewAnimationTransitionCurlDown forView: cache espaço reservado: YES];
; [TView removeFromSuperview];
fview ] ; [Espaço reservado addSubview: fview];
; [Fview removeFromSuperview];
tview ] ; [Espaço reservado addSubview: TView];
; [UIView commitAnimations];
}

Ele pode ser usado da seguinte maneira:

1
2
3
4
/ Display / - Scroll para a frente
window fromView : primaView.view toView : secondaView.view forward : YES ] ; [Self makeTansitionFromView: Janela fromView: primaView.view toView: secondaView.view frente: YES];
/ / Hide - percorrer de volta
window fromView : secondaView.view toView : primaView.view forward : NO ] ; [Self makeTansitionFromView: Janela fromView: secondaView.view toView: primaView.view frente: NÃO];

3. Evitar auto escurecimento da tela

Para ser usado com cuidado, sob pena de consumo imediato da bateria, esta linha de código faz com que seja possível manter a nossa aplicação sempre visível, impedindo que o iPhone da Apple entra em "standby"

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

4. Indicador de atividade da rede

A animação que aparece na barra de status na parte superior da tela do iPhone da Apple, também pode ser usado para destacar uma aplicação em nossa rede:

1
2
3
4
5
6
7
/ Indicador de Atividade / Show da rede ...
.networkActivityIndicatorVisible = YES ; [SharedApplication UIApplication] NetworkActivityIndicatorVisible = YES.;

/ / Suas operações ...

/ / Hide Indicador de Atividade de Rede ...
.networkActivityIndicatorVisible = NO ; [SharedApplication UIApplication] NetworkActivityIndicatorVisible = NO.;

5. Indicador de Atividade pessoais

Se você não tem a barra de status, pode ser útil para mostrar um de nossos Indicador de Atividade:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/ / Global em algum lugar ... Édipo em um Delegado (. H)
* Atividade UIActivityIndicatorView;

/ / Inicializar o viewDidLoad Em loadview ou Indicador de Atividade
UIActivityIndicatorView alloc ] initWithActivityIndicatorStyle : UIActivityIndicatorViewStyleWhite ] ; atividade = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
activity ] ; [Self.view addSubview: atividade];
CGPointMake ( 160 , 240 ) ] ; [Atividade setCenter: CGPointMake (160, 240)];
; [Atividade StopAnimating];

/ / Quando precisamos
void ) someMethod { - (Void) {someMethod
; [Atividade StartAnimating];
/ / Para fazer ...
; [Atividade StopAnimating];
}

6. Localização

Com esse trecho que você pode entender que a "linguagem" está definido nosso dispositivo:

1
2
3
4
5
6
7
/ / Verificação de linguagem e localização
defaults = [ NSUserDefaults standardUserDefaults ] ; NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults];
languages = [ defaults objectForKey : @ "AppleLanguages" ] ; NSArray * línguas = [defaults objectForKey: @ "AppleLanguages"];
currentLanguage = [ languages objectAtIndex : 0 ] ; NSString * currentLanguage = [línguas objectAtIndex: 0];

"Current Locale: %@" , [ [ NSLocale currentLocale ] localeIdentifier ] ) ; NSLog (@ "Local atual:% @", [[ NSLocale currentLocale] LocaleIdentifier]);
"Current language: %@" , currentLanguage ) ; NSLog (@ "linguagem atual:% @", currentLanguage);

7. iPhone ou iPod?

Esta classe é útil para determinar qual dispositivo da Apple está em execução a nossa aplicação. Não só podemos determinar o modelo (iPhone ou iPod Touch), mas também a versão. : Criar dois arquivos UIDevice-hardware.h e UIDevice-hardware.m :

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

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

Hardware ) @ Interface UIDevice (Hardware)
NSString * ) platform; - ( NSString *) 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>
# Include <sys/sysctl.h>

Hardware ) @ Implementação UIDevice (Hardware)

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

NSString * ) platform { - ( NSString *) plataforma {
tamanho size_t;
, NULL , & size, NULL , 0 ) ; sysctlbyname ("hw.machine", NULL, & tamanho, NULL, 0);
machine = malloc ( size ) ; char * máquina = malloc (tamanho);
, machine, & size, NULL , 0 ) ; ysctlbyname ("hw.machine", máquinas, e tamanho, NULL, 0);
platform = [ NSString stringWithCString : machine ] ; NSString * plataforma = [ NSString stringWithCString: máquina];
machine ) ; livre (máquina);
retorno da plataforma;
}

NSString * ) platformString { - ( NSString *) {platformString
platform = [ self platform ] ; NSString * plataforma = [plataforma self];
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;
; retornar NULL;
}
@ End

Em nossa delegação para entrar:

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

8. Sala

Quando você escrever um aplicativo que usa o acesso às funções da Câmara é para verificar se o "aparelho" suporta esses recursos (conforme diretrizes 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 Auto: self.imgPicker animado: YES];
}

9. Álbuns de Fotos & Photo Library

Semelhante ao que acontece com a Câmara, é melhor basta verificar quando você acessar a biblioteca de imagens:

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 Auto: self.imgPicker animado: YES];
}
/ / Ou ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypePhotoLibrary ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imgPicker animated : YES ] ; [PresentModalViewController Auto: self.imgPicker animado: YES];
}

10. Disponibilidade e tipo de rede

Felizmente, a Apple tem escrito uma classe para nós para determinar o status da rede. Isto pode ser usado em nossa aplicação é verificar que a sua topologia de rede: Ethernet ou Wi-Fi. Download Reachability.h e Reachability.m . Adicione o quadro SystemConfiguration.framework . Aqui você pode escrever uma função como:

1
2
3
4
5
6
7
8
9
10
/ / No seu Delegado. H
@ Acessibilidade de classe;
/ /
/ / Delegados pol M
# Import "Reachability.h"

/ / Verifique a cobertura de rede
BOOL ) CheckNetworkStatus { - (BOOL) {CheckNetworkStatus
Reachability reachabilityForInternetConnection ] retain ] != NotReachable ) ; return ([[reachabilityForInternetConnection acessibilidade] reter] = NotReachable!);
}

Por favor, note que o código da Apple, que está disponível na fonte completo Reachability.zip é para SDK 3.1.2. Se você tentar preencher para SDK 2.2.1 você precisa comentar sobre algumas partes do código não são suportados pelo "velho" (mesmo que eles ainda existem) SDK, como define:

1
2
kSCNetworkReachabilityFlagsConnectionOnTraffic
kSCNetworkReachabilityFlagsConnectionOnDemand

eo pedaço de código (por comentário):

1
2
3
4
5
6
7
8
9
10
11
12
/ / Se ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) = 0)! | |
/ / (Flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)! = 0))
/ / {
/ / / / ... ea conexão é on-demand (ou em trânsito) se o
/ / / / Aplicativo de chamada está usando as APIs ou superior CFSocketStream
/ /
/ / Se ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
/ / {
/ / / / ... e não [usuário] intervenção é necessária
/ / = RetVal ReachableViaWiFi;
/ /}
/ /}

Não há comentários para este post

Deixe um comentário

XHTML PERMIT TAG: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> CÓDIGO DE INSERÇÃO:
 <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 


Parar SOPA