iphone代碼集2

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];
    
//
這段代碼可以正確顯示圖片。



1. 隨機數:
srandom(time(NULL)); //隨機數種子

id d 
= random(); // 隨機數

 

  2. 視頻播放:

    MPMoviePlayerController *moviePlayer;
    moviePlayer 
=
 [[MPMoviePlayerController alloc]
                   initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:
@"Movie" ofType:@"m4v"
]]];
    
//初始化視頻播放器對象,並傳入被播放文件的地址

    moviePlayer.movieControlMode = MPMovieControlModeDefault;
    [moviePlayer play];
    
//此處有內存溢出

 

   3.  啓動界面顯示:

iPhone軟件啓動後的第一屏圖片是非常重要的往往就是loading載入中的意思。設置它說來也簡單,但是卻無比重要

只需要在resource裏面將你希望設置的圖片更名爲Default.png,這個圖片就可以成爲iPhone載入的缺省圖片

 

    4. iPhone的系統目錄:

//得到Document目錄:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString 
*documentsDirectory = [paths objectAtIndex:0
];

//得到temp臨時目錄:

NSString *tempPath = NSTemporaryDirectory();

//得到目錄上的文件地址:

NSString *文件地址 = [目錄地址 stringByAppendingPathComponent:@"文件名.擴展名"];

 

    5. 狀態欄顯示Indicator:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

 

  6.app Icon顯示數字:

 

- (void)applicationDidEnterBackground:(UIApplication *)application{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:
5
];
}

 

   7.sqlite保存地址:

 

 

代碼
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString 
*thePath = [paths objectAtIndex:0
];
    NSString 
*filePath = [thePath stringByAppendingPathComponent:@"kilonet1.sqlite"
];
    
    NSString 
*dbPath =
 [[[NSBundle mainBundle] resourcePath]
                        stringByAppendingPathComponent:
@"kilonet2.sqlite"];  

 

   8.Application退出:exit(0);

      9. AlertView,ActionSheet的cancelButton點擊事件:

代碼
-(void) actionSheet :(UIActionSheet *) actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex {
    NSLog(
@"cancel actionSheet........"
);
    
//當用戶按下cancel按鈕

    if( buttonIndex == [actionSheet cancelButtonIndex]) {
        exit(
0
);
    }
//    //
當用戶按下destructive按鈕
//
    if( buttonIndex == [actionSheet destructiveButtonIndex]) {
//        //
 DoSomething here.
//    }

}

- (void)alertView:(UIAlertView *
)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
     NSLog(
@"cancel alertView........"
);
    
if (buttonIndex ==
 [alertView cancelButtonIndex]) {
        exit(
0
);
    }
}

 

    10.給Window設置全局的背景圖片:

window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"coolblack.png"]];

 

    11. UITextField文本框顯示及對鍵盤的控制:

iPhone代碼片段收集 - yueding920 - 王凱鋒的博客代碼
#pragma mark -
#pragma mark UITextFieldDelegate 
//控制鍵盤跳轉
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   
    
if (textField ==
 _txtAccount) {
        
if ([_txtAccount.text length]==0
) {
            
return
 NO;
        }
        [_txtPassword becomeFirstResponder];
    } 
else if (textField ==
 _txtPassword) {
        [_txtPassword resignFirstResponder];
    }
    
    
return
 YES;
}

//輸入框背景更換

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
    
    [textField setBackground:[UIImage imageNamed:
@"ctext_field_02.png"
]];
    
    
return
 YES;
}

-(void) textFieldDidEndEditing:(UITextField *
)textField{
    [textField setBackground:[UIImage imageNamed:
@"ctext_field_01.png"
]];
}

 

    12.UITextField文本框前面空白寬度設置以及後面組合按鈕設置:

代碼
    //給文本輸入框後面加入空白
    _txtAccount.rightView = _btnDropDown;
    _txtAccount.rightViewMode 
=
  UITextFieldViewModeAlways;
    
    
//給文本輸入框前面加入空白

    CGRect frame = [_txtAccount frame];
    frame.size.width 
= 5
;
    UIView 
*leftview =
 [[UIView alloc] initWithFrame:frame];
    _txtAccount.leftViewMode 
=
 UITextFieldViewModeAlways;
    _txtAccount.leftView 
= leftview;

 

    13. UIScrollView 設置滑動不超出本身範圍:

 [fcScrollView setBounces:NO]; 

     14. 遍歷View裏面所有的Subview:

iPhone代碼片段收集 - yueding920 - 王凱鋒的博客代碼
    NSLog(@"subviews count=%d",[self.view.subviews count]);
    
if ([self.view.subviews count] > 0
) {
        
for (UIView *curView in
 self.view.subviews) {
                       NSLog(@
"view.subviews=%@"
, [NSString stringWithUTF8String:object_getClassName(curView)]);
        }
    }

 

    14. 在drawRect裏畫文字:

     UIFont * f = [UIFont systemFontOfSize:20]; 

    [[UIColor darkGrayColor] set]; 

    NSString * text = @"hi /nKiloNet"

    [text drawAtPoint:CGPointMake(center.x,center.y) withFont:f];

 

    15. NSArray查找是否存在對象時用indexOfObject,如果不存在則返回爲NSNotFound.

 

     16. NString與NSArray之間相互轉換:

array = [string componentsSeparatedByString:@","];
string = [[array valueForKey:@"description"] componentsJoinedByString:@","];

 

     17. TabController隨意切換tab bar:

[self.tabBarController setSelectedIndex:tabIndex];

或者 self.tabBarController.selectedIndex = tabIndex;

或者實現下面的delegate來撲捉tab bar的事件:

代碼
-(BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    
if ([viewController.tabBarItem.title isEqualToString: NSLocalizedString(@"Logout"
,nil)]) {
        [self showLogout];
        
return
 NO;
    }
    
return
 YES;
}

 

 

    18. 自定義View之間切換動畫:
代碼
- (void) pushController: (UIViewController*) controller
         withTransition: (UIViewAnimationTransition) transition
{
    [UIView beginAnimations:nil context:NULL];
    [self pushViewController:controller animated:NO];
    [UIView setAnimationDuration:.
5
];
    [UIView setAnimationBeginsFromCurrentState:YES];        
    [UIView setAnimationTransition:transition forView:self.view cache:YES];
    [UIView commitAnimations];
}

    或者:

代碼
CATransition *transition = [CATransition animation];
transition.duration 
=
 kAnimationDuration;
transition.timingFunction 
=
 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type 
=
 kCATransitionPush;
transition.subtype 
=
 kCATransitionFromTop;
transitioning 
=
 YES;
transition.
delegate =
 self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
    
self.navigationController.navigationBarHidden 
=
 NO;
[self.navigationController pushViewController:tableViewController animated:YES];


      19. UIWebView加載時白色顯示問題解決以及字體統一設置:

    uiWebView.opaque = NO; 

 代碼

 

     20.計算字符串長度:

CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size:18]].width; 

 

    21. iTunesLink should be your applications link

NSString *iTunesLink = @"http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=xxxxxx&mt=8";

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];


    22.時間轉換NSString & NSDate:

 -(NSDate *)NSStringDateToNSDate:(NSString *)string {    

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *date = [formatter dateFromString:string];

    [formatter release];

    return date;

}

 NSString *year = [myDate descriptionWithCalendarFormat:@"%Y" timeZone:nil locale:nil];

or
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];

//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

 22。 模擬器的文件位置

其中#username#表示當前用戶名:
/Users/#username#/Library/Application Support/iPhone Simulator/User/Applications/

 

  23.在使用UISearchBar時,將背景色設定爲clearColor,或者將translucent設爲YES,都不能使背景透明,經過一番研究,發現了一種超級簡單和實用的方法:

1
[[searchbar.subviews objectAtIndex:0]removeFromSuperview];

背景完全消除了,只剩下搜索框本身了。 

 

   24.  圖像與緩存 :

UIImageView *wallpaper = [[UIImageView alloc] initWithImage:

        [UIImage imageNamed:@"icon.png"]]; // 會緩存圖片

 

UIImageView *wallpaper = [[UIImageView alloc] initWithImage:

        [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不會緩存圖片 

 

  25. iphone-常用的對視圖圖層(layer)的操作

對圖層的操作:

(1.給圖層添加背景圖片:
myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage;

(2.將圖層的邊框設置爲圓腳
myWebView.layer.cornerRadius = 8;
myWebView.layer.masksToBounds = YES;

(3.給圖層添加一個有色邊框
myWebView.layer.borderWidth = 5;
myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];


 26. UIPopoverController 使用

 

-(void) onSetting:(id) sender {


    SplitBaseController *detail = [[SettingServerController alloc] init];


    

    CGRect frame = [(UIView *)sender frame];

    frame.origin.y = 0;

    

    UIPopoverController *popwin = [[UIPopoverController alloc] initWithContentViewController:detail];

    [popwin setPopoverContentSize:CGSizeMake(400, 300) animated:YES];

    popwin.delegate = self;

    [popwin presentPopoverFromRect: frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];


    [detail release];

} 

 

 27.在UINavigationBar中添加左箭頭返回按鈕


iPhone裏面最討厭的控件之一就是 UINavigationBar了。這個控件樣式修改不方便,連添加按鈕也特別麻煩。下面的例子是如何手動添加帶箭頭的按鈕:


UINavigationItem *item = [navBar.items objectAtIndex:0];

UINavigationItem *back = [[UINavigationItem alloc] initWithTitle:@"Back"];

NSArray *items = [[NSArray alloc] initWithObjects:back,item,nil];

[navBar setItems:items];


- (BOOL)navigationBar:(UINavigationBar *)navigationBar

shouldPopItem:(UINavigationItem *)item{

//在此處添加點擊back按鈕之後的操作代碼 

return NO;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章