2011年2月15日 星期二

iPhone代碼片段收集(持續更新)


  1. stringWithFormat 用法:

     [NSString stringWithFormat:@"Hight: %d°%@   Low: %d°%@", [Temp],@"C",[lTemp],@"C"];

       NSString to NSData:

NSString* str= @"kilonet";

NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding]; 

     2. NSDate 用法:
         NSDate  *today;
    NSDate *tomorrow;
    today 
= [NSDate date];
    tomorrow 
= [NSDate dateWithTimeInterval:(i*24*60*60) sinceDate:today]; //可能有更好的

         Date format用法:
  -(NSString *) getDay:(NSDate *) d {
    NSString *s ;
    NSDateFormatter 
*format = [[NSDateFormatter alloc] init];
    [format setDateFormat:
@"YYYY/MM/dd hh:mm:ss"];
    s 
= [format stringFromDate:d];
    [format release];
    
return s;
}

    各地時區獲取:
    NSDate *nowDate = [NSDate new];
    NSDateFormatter *formatter    =  [[NSDateFormatter alloc] init];
    [formatter    setDateFormat:
@"yyyy/MM/dd HH:mm:ss"];
    
//    根據時區名字獲取當前時間,如果該時區不存在,默認獲取系統當前時區的時間
    
//    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Europe/Andorra"];  
    
//    [formatter setTimeZone:timeZone];
    
//獲取所有的時區名字
    NSArray *array = [NSTimeZone knownTimeZoneNames];
    
//    NSLog(@"array:%@",array);
    
//for循環
    
//    for(int i=0;i<[array count];i++)
    
//    {
    
//        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:[array objectAtIndex:i]];
    
//        [formatter setTimeZone:timeZone];
    
//        NSString *locationTime = [formatter stringFromDate:nowDate];
    
//        NSLog(@"時區名字:%@   : 時區當前時間: %@",[array objectAtIndex:i],locationTime);
    
//        //NSLog(@"timezone name is:%@",[array objectAtIndex:i]);
    
//    }  
    
//快速枚舉法
    for(NSString *timeZoneName in array){
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:timeZoneName]];
        NSLog(
@"%@,%@",timeZoneName,[formatter stringFromDate:nowDate]);
    }
  
    [formatter release];
    [nowDate release];

     獲取毫秒時間:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    
//[dateFormatter setDateFormat:@"hh:mm:ss"]
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSLog(
@"Date%@", [dateFormatter stringFromDate:[NSDate date]]);
    [dateFormatter release];


     
      3. NSCalendar用法:
 -(NSString *) getWeek:(NSDate *) d {
  
    NSCalendar 
*calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned units 
= NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents 
*components = [calendar components:units fromDate:d];
    [calendar release];
  
    
switch ([components weekday]) {
        
case 2:
            
return @"Monday";
            
break;
        
case 3:
            
return @"Tuesday";
            
break;
        
case 4:
            
return @"Wednesday";
            
break;
        
case 5:
           
return @"Thursday";
            
break;
        
case 6:
            
return  @"Friday";
            
break;
        
case 7:
            
return  @"Saturday";
            
break;
        
case 1:
            
return @"Sunday";
            
break;
        
default:
            
return @"No Week";
            
break;
    }

    
// 用components,我們可以讀取其他更多的數據。
  
}

      4. 用Get方式讀取網絡數據:
// 將網絡數讀取為字符串
- (NSString *) getDataByURL:(NSString *) url {
    
return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
}
//讀取網絡圖片
- (UIImage *) getImageByURL:(NSString *) url {
    
return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}


     5. 多線程NSThread用法 :
[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];

-(void) scheduleTask {
    
//create a pool 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    
//release the pool;
    [pool release];
}
//如果有參數,則這麼使用:
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];

-(void) scheduleTask:(NSDate *) mdate {
    
//create a pool 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    
//release the pool;
    [pool release];
}
//注意selector裡有冒號。
    //在線程裡運行主線程裡的方法 
    [self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];


      6. 定時器NSTimer用法:
  // 一個可以自動關閉的Alert窗口

    UIAlertView 
*alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:[
@"一個可以自動關閉的Alert窗口"
                                                   
delegate:nil
                                          cancelButtonTitle:nil 
//NSLocalizedString(@"OK", @"OK")   //取消任何按鈕
                                          otherButtonTitles:nil];
    
//[alert setBounds:CGRectMake(alert.bounds.origin.x, alert.bounds.origin.y, alert.bounds.size.width, alert.bounds.size.height+30.0)];
    [alert show];
  
    UIActivityIndicatorView 
*indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  
    
// Adjust the indicator so it is up a few pixels from the bottom of the alert    
    indicator.center = CGPointMake(alert.bounds.size.width/2,  alert.bounds.size.height-40.0);
    [indicator startAnimating];
    [alert insertSubview:indicator atIndex:
0];
    [indicator release];
  
    [NSTimer scheduledTimerWithTimeInterval:
3.0f
                                     target:self
                                   selector:@selector(dismissAlert:)
                                   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alert, 
@"alert"@"testing "@"key" ,nil]  //如果不用傳遞參數,那麼可以將此項設置為nil.
                                    repeats:NO];

    NSLog(
@"release alert");
    [alert release];

-(void) dismissAlert:(NSTimer *)timer{
  
    NSLog(
@"release timer");
    NSLog([[timer userInfo]  objectForKey:
@"key"]);
  
    UIAlertView 
*alert = [[timer userInfo]  objectForKey:@"alert"];
    [alert dismissWithClickedButtonIndex:
0 animated:YES];
 
}

       定時器停止使用:
        [timer invalidate];
        timer 
= nil;



     7. 用戶缺省值NSUserDefaults讀取:
    //得到用戶缺省值
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
  
    
//在缺省值中找到AppleLanguages, 返回值是一個數組
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSLog(
@"all language語言 is %@", languages);
  
    
//在得到的數組中的第一個項就是用戶的首選語言了
    NSLog(@"首選語言 is %@",[languages objectAtIndex:0]);



    
//get the language & country code
    NSLocale *currentLocale = [NSLocale currentLocale];
  
    NSLog(
@"Language Code is %@", [currentLocale objectForKey:NSLocaleLanguageCode]);  
    NSLog(
@"Country Code is %@", [currentLocale objectForKey:NSLocaleCountryCode]);    


     8. View之間切換的動態效果設置:
    SettingsController *settings = [[SettingsController alloc]initWithNibName:@"SettingsView" bundle:nil];
    settings.modalTransitionStyle 
= UIModalTransitionStyleFlipHorizontal;  //水平翻轉
    [self presentModalViewController:settings animated:YES];
    [settings release];


     9.NSScrollView 滑動用法:
-(void) scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(
@"正在滑動中...");
}
//用戶直接滑動NSScrollView,可以看到滑動條
-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

}
// 通過其他控件觸發NSScrollView滑動,看不到滑動條
- (void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

}

   
    10. 讀取全局的Delegate:
KiloNetAppDelegate *appdelegate = (KiloNetAppDelegate *)[[UIApplication sharedApplication] delegate];

     11.鍵盤處理系列
 //set the UIKeyboard to switch to a different text field when you press return

//switch textField to the name of your textfield
[textField becomeFirstResponder];

     12. 半透明層的實現:
+(void)showWaiting:(UIView *)parent {
    
int width = 32, height = 32;
  
    CGRect frame 
= [parent frame]; //[[UIScreen mainScreen] applicationFrame];
    int x = frame.size.width;
    
int y = frame.size.height;
  
    frame 
= CGRectMake((x - width) / 2, (y - height) / 2, width, height);
    UIActivityIndicatorView
* progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    [progressInd startAnimating];
    progressInd.activityIndicatorViewStyle 
= UIActivityIndicatorViewStyleWhiteLarge;
  
    
//    frame = CGRectMake((x - 140)/2, (y - height) / 2 + height, 140, 30);//    UILabel *waitingLable = [[UILabel alloc] initWithFrame:frame];//    waitingLable.text = @"Proccesing...";//    waitingLable.textColor = [UIColor whiteColor];//    waitingLable.font = [UIFont systemFontOfSize:15];//    waitingLable.backgroundColor = [UIColor clearColor];
  
    frame 
= [parent frame];
    UIView 
*theView = [[UIView alloc] initWithFrame:frame];
    theView.backgroundColor 
= [UIColor blackColor];
    theView.alpha 
= 0.8;
  
    [theView addSubview:progressInd];
//  [theView addSubview:waitingLable];
  
    [progressInd release];
//    [waitingLable release];
  
    [theView setTag:
9999];
    [parent addSubview:theView];
    [theView release];
}
+(void)hideWaiting:(UIView *)parent {
    [[parent viewWithTag:
9999] removeFromSuperview];
}

      13. 設置View的圓角:
 // 首先應用  #import <QuartzCore/QuartzCore.h>
view.layer.cornerRadius = 10;
view.layer.masksToBounds 
= YES;

      14. UIWebView顯示本地圖片(目前有點問題,無法正確顯示圖片):
    NSString *imagePath = [[NSBundle mainBundle] resourcePath];
    imagePath 
= [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
    imagePath 
= [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
  
    NSLog(
@"fileurl=%@",[NSString stringWithFormat:@"file:/%@//",imagePath]);
  
    
//[self loadData:[html dataUsingEncoding:NSUTF8StringEncoding] MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"file:/%@//",imagePath]] ];
    [self loadHTMLString:html baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"file:/%@//",imagePath]   ]];
     NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    [UIWebView loadHTMLString:html baseURL:baseURL];
    
//這段代碼可以正確顯示圖片。

沒有留言:

張貼留言