Mostrando postagens com marcador Função. Mostrar todas as postagens
Mostrando postagens com marcador Função. Mostrar todas as postagens

segunda-feira, 9 de julho de 2012

Função - Retorna UIColor a partir do código RGB

Função que retorna uma cor (UIColor) passando apenas o código RGB. Esta função é bem parecida com a original, mas os valores dos parâmetros são de 1 até 255 e não uma porcentagem (ex. 0.7). E isto realmente facilita.


  1. +(UIColor *)ColorWithRed:(int)r andGreen:(int)g andBlue:(int)b andAlpha:(float)a
  2. {
  3.     return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
  4. }
  5.  


quarta-feira, 4 de julho de 2012

Função - Retorna uma NSString (hh:mm:ss) passando apenas os segundos

Função que retorna uma string (NSString) no formato de horário apenas passando a quantidade de segundos.
Barbada galera!



  1. +(NSString *)clockFormatWithSeconds:(int)seconds
  2. {
  3.     int hour = 0, min = 0, sec = 0;
  4.     NSString *h, *m, *s;
  5.  
  6.     sec = seconds;
  7.  
  8.     while (sec >= 60) {min+=1; sec-=60;}
  9.     while (min >= 60) {hour+=1; min-=60;}
  10.  
  11.     h = (hour > 9) ? [NSString stringWithFormat:@"%d",hour] : [NSString stringWithFormat:@"0%d",hour] ;
  12.     m = (min > 9) ? [NSString stringWithFormat:@"%d",min] : [NSString stringWithFormat:@"0%d",min] ;
  13.     s = (sec > 9) ? [NSString stringWithFormat:@"%d",sec] : [NSString stringWithFormat:@"0%d",sec] ;
  14.  
  15.     return [NSString stringWithFormat:@"%@:%@:%@",h,m,s];
  16. }


sexta-feira, 29 de junho de 2012

Função - Redimensionar UIImage

Função para redimensionar  imagens (UIImage).


  1. +(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
  2. {
  3.     UIGraphicsBeginImageContext(newSize);
  4.     [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
  5.     UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  6.     UIGraphicsEndImageContext();
  7.     return newImage;
  8. }




segunda-feira, 25 de junho de 2012

Função - Embaralhar NSMutableArray

Função para você embaralhar um NSMutableArray um determinado número de vezes.

  1. //Aplicação do método
  2. NSMutableArray * array = [[NSMutableArray alloc]  initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
  3. [self shuffleMutableArray:&array frequency:10];
  4.  
  5. //Método para embaralhar arrays
  6. +(void)shuffleMutableArray:(NSMutableArray **)array frequency:(int)f
  7. {    
  8.     for (int i = 0; i < f; i++) {
  9.         int randA,randB;
  10.         do {
  11.             randA = (random() % [*array count] -i)+i;
  12.             randB = (random() % [*array count] -i)+i;
  13.         } while (randA==randB);        
  14.         [*array exchangeObjectAtIndex:randA withObjectAtIndex:randB];
  15.     }
  16. }
  17.  


sexta-feira, 24 de fevereiro de 2012

Função - Pegar a versão do projeto

  1. //Retorna uma NSString com a versão que está o projeto.
  2. [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"];




sábado, 10 de dezembro de 2011

Função - Formatar horário a partir de X segundos


//  ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    // Criando um processo para chamar o métodos onTimer a cada 1 segundo
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

- (void)onTimer
{
    static int segundos = 0;
    
    segundos++;
        
    // Imprimi no console o horário formatado
    NSLog(@"%@",[self horarioFormatadaComSegundos:segundos]);
}

// Função para formatar um horário a partir de inteiros.
- (NSString *)horarioFormatadaComSegundos:(int)segundos
{
    int hor = 0, min = 0, seg = 0;
    
    seg = segundos;
    
    while (seg >= 60) { min+=1; seg-=60; }
    
    while (min >= 60) { hor+=1; min-=60; }
    
    NSString * h, * m, * s;
    
    h = (hor > 9) ? [NSString stringWithFormat:@"%d",hor] : [NSString stringWithFormat:@"0%d",hor] ;
    m = (min > 9) ? [NSString stringWithFormat:@"%d",min] : [NSString stringWithFormat:@"0%d",min] ;
    s = (seg > 9) ? [NSString stringWithFormat:@"%d",seg] : [NSString stringWithFormat:@"0%d",seg] ;
    
    return [NSString stringWithFormat:@"%@:%@:%@",h,m,s];
}


terça-feira, 29 de novembro de 2011

Função - Gerando números aleatórios


srand(time(NULL));                 // Sequência que nunca se repete
    
for (int i = 0; i < 10; i++)      
{
    int r = rand()%100;            // Gerando número aleatório de 0 à 100.
        
    NSLog(@"%d",r);                // Imprimindo resposta
}





srand(100);                        // Sequência que sempre se repete
    
for (int i = 0; i < 10; i++)     
{
    int r = rand()%100;            // Gerando número aleatório de 0 à 100.
        
    NSLog(@"%d",r);                // Imprimindo resposta
}



Função - Alerta simples com Título e Mensagem


// ViewController.m

- (IBAction)btnTouched:(id)sender 
{
    [self AlertWithTitle:@"Mensagem" andAlert:@"Isto é um teste!"];
}

// Retorna uma mensagem simples apenas com título e mensagem
-(void)AlertWithTitle:(NSString *)title_ andAlert:(NSString *)alert_
{
    [[[[UIAlertView alloc] initWithTitle:title_ message:alert_ delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] autorelease] show];
}





Função para abrir uma URL no Safari


// ViewController.m

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self abrirNoSafari:@"http://www.google.com.br"];
    
}


// Função criada
- (void)abrirNoSafari:(NSString *)site
{
    NSURL * url = [NSURL URLWithString:site]; // Transformando a string para url
    
    if (![[UIApplication sharedApplication] openURL:url]) // Tenta abrir o site no safari
    {
        NSLog(@"Falhou ao tentar abrir o site: %@",site); // Mensagem de erro
    }
}