天天看點

iOS/SWIFT開發常用的代碼

iOS開發常用的代碼

%c 一個單一的字元

%d 一個十進制整數

%i 一個整數

%e, %f, %g 一個浮點數

%o 一個八進制數

%s 一個字元串

%x 一個十六進制數

%p 一個指針

%n 一個等于讀取字元數量的整數

%u 一個無符号整數

%[] 一個字元集

%% 一個精度符号

//一、NSString

    1、建立常量字元串。

    NSString*astring = @"This is a String!";

    2、建立空字元串,給予指派。

    NSString*astring = [[NSString alloc] init];

    astring [email protected]"This is a String!";

   NSLog(@"astring:%@",astring);

    [astringrelease];

    3、在以上方法中,提升速度:initWithString方法

    NSString*astring = [[NSString alloc] initWithString:@"This is a String!"];

   NSLog(@"astring:%@",astring);

    [astringrelease];

    4、用标準c建立字元串:initWithCString方法

    char *Cstring ="This is a String!";

    NSString*astring = [[NSString alloc] initWithCString:Cstring];

   NSLog(@"astring:%@",astring);

    [astringrelease];

    5、建立格式化字元串:占位符(由一個%加一個字元組成)

    int i = 1;

    int j = 2;

    NSString*astring = [[NSString alloc]

                       initWithString:[NSString stringWithFormat:@"%d.This is %istring!",i,j]];

   NSLog(@"astring:%@",astring);

    [astringrelease];

    6、建立臨時字元串

    NSString*astring;

    astring =[NSString stringWithCString:"This is a temporary string"];

   NSLog(@"astring:%@",astring);

    NSString *path= @"astring.text";

    NSString*astring = [[NSString alloc] initWithContentsOfFile:path];

   NSLog(@"astring:%@",astring);

    [astringrelease];

    NSString*astring = [[NSString alloc] initWithString:@"This is a String!"];

   NSLog(@"astring:%@",astring);

    NSString *path= @"astring.text";

    [astringwriteToFile: path atomically: YES];

    [astringrelease];   

    用C比較:strcmp函數

    char string1[]= "string!";

    char string2[]= "string!";

   if(strcmp(string1, string2) = = 0)

    {

       NSLog(@"1");

    }

    isEqualToString方法

    NSString*astring01 = @"This is a String!";

    NSString*astring02 = @"This is a String!";

    BOOL result =[astring01 isEqualToString:astring02];

   NSLog(@"result:%d",result);

    compare方法(comparer傳回的三種值)

    NSString*astring01 = @"This is a String!";

    NSString*astring02 = @"This is a String!";

    BOOL result =[astring01 compare:astring02] = = NSOrderedSame;

   NSLog(@"result:%d",result);

    NSOrderedSame 判斷兩者内容是否相同

    NSString*astring01 = @"This is a String!";

    NSString*astring02 = @"this is a String!";

    BOOL result =[astring01 compare:astring02] = = NSOrderedAscending;

   NSLog(@"result:%d",result);

   //NSOrderedAscending 判斷兩對象值的大小(按字母順序進行比較,astring02大于astring01為真)

    NSString*astring01 = @"this is a String!";

    NSString*astring02 = @"This is a String!";

    BOOL result =[astring01 compare:astring02] = = NSOrderedDescending;

   NSLog(@"result:%d",result);

   //NSOrderedDescending 判斷兩對象值的大小(按字母順序進行比較,astring02小于astring01為真)

    不考慮大 小寫比較字元串1

    NSString*astring01 = @"this is a String!";

    NSString*astring02 = @"This is a String!";

    BOOL result =[astring01 caseInsensitiveCompare:astring02] = = NSOrderedSame;

   NSLog(@"result:%d",result);

   //NSOrderedDescending判斷兩對象值的大小(按字母順序進行比較,astring02小于astring01為 真)

    不考慮大小寫比較字元串2

    NSString*astring01 = @"this is a String!";

    NSString*astring02 = @"This is a String!";

    BOOL result =[astring01 compare:astring02

                           options:NSCaseInsensitiveSearch | NSNumericSearch] = = NSOrderedSame;

   NSLog(@"result:%d",result);    

   //NSCaseInsensitiveSearch:不區分大小寫比較 NSLiteralSearch:進行完全比較,區分大小寫NSNumericSearch:比較字元串的字元個數,而不是字元值。

    NSString*string1 = @"A String";

    NSString*string2 = @"String";

   NSLog(@"string1:%@",[string1 uppercaseString]);//大寫

   NSLog(@"string2:%@",[string2 lowercaseString]);//小寫

   NSLog(@"string2:%@",[string2 capitalizedString]);//首字母大小

    NSString*string1 = @"This is a string";

    NSString*string2 = @"string";

    NSRange range =[string1 rangeOfString:string2];

    int location =range.location;

    int leight =range.length;

    NSString*astring = [[NSString alloc]

                       initWithString:[NSStringstringWithFormat:@"Location:%i,Leight:%i"

                       ,location,leight]];

   NSLog(@"astring:%@",astring);

    [astringrelease];

    -substringToIndex:從字元串的開頭一直截取到指定的位置,但不包括該位置的字元

    NSString*string1 = @"This is a string";

    NSString*string2 = [string1 substringToIndex:3];

   NSLog(@"string2:%@",string2);

   -substringFromIndex: 以指定位置開始(包括指定位置的字元),并包括之後的全部字元

    NSString*string1 = @"This is a string";

    NSString*string2 = [string1 substringFromIndex:3];

   NSLog(@"string2:%@",string2);

   -substringWithRange: //按照所給出的位置,長度,任意地從字元串中截取子串

    NSString*string1 = @"This is a string";

    NSString*string2 = [string1 substringWithRange:NSMakeRange(0, 4)];

   NSLog(@"string2:%@",string2);

const char *fieldValue = [value  cStringUsingEncoding:NSUTF8StringEncoding];

const char *fieldValue = [value UTF8String];

NSString 轉NSData

NSString* str= @"kilonet";

NSData* data=[strdataUsingEncoding:NSUTF8StringEncoding];

   Date format用法:

  -(NSString *)getDay:(NSDate *) d

{

    NSString *s ;

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

    [formatsetDateFormat:@"YYYY/MM/dd hh:mm:ss"];

    s = [formatstringFromDate:d];

    [formatrelease];

    return s;

}

各地時區擷取:

NSDate *nowDate = [NSDate new];

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

    [formatter    setDateFormat:@"yyyy/MM/ddHH:mm:ss"];

    //    根據時區名字擷取目前時間,如果該時區不存在,預設擷取系統目前時區的時間

    //    NSTimeZone* timeZone = [NSTimeZonetimeZoneWithName:@"Europe/Andorra"];

    //    [formatter setTimeZone:timeZone];

    //擷取所有的時區名字

    NSArray *array= [NSTimeZone knownTimeZoneNames];

    //    NSLog(@"array:%@",array);

    //for循環

    //    for(int i=0;i<[array count];i++)

    //    {

    //        NSTimeZone* timeZone = [NSTimeZonetimeZoneWithName:[array objectAtIndex:i]];

    //        [formatter setTimeZone:timeZone];

    //        NSString *locationTime = [formatterstringFromDate:nowDate];

    //        NSLog(@"時區名字:%@  : 時區目前時間: %@",[arrayobjectAtIndex:i],locationTime);

    //        //NSLog(@"timezone nameis:%@",[array objectAtIndex:i]);

    //    }

    //快速枚舉法

    for(NSString*timeZoneName in array){

        [formattersetTimeZone:[NSTimeZone timeZoneWithName:timeZoneName]];

       NSLog(@"%@,%@",timeZoneName,[formatterstringFromDate:nowDate]);

    }

    [formatterrelease];

    [nowDate release];

 NSCalendar用法:

 -(NSString *)getWeek:(NSDate *) d {

    NSCalendar*calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

    unsigned units= NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;

   NSDateComponents *components = [calendar components:units fromDate:d];

    [calendarrelease];

    switch([components weekday]) {

        case 2:

            [email protected]"Monday";

            break;

        case 3:

            [email protected]"Tuesday";

            break;

        case 4:

            [email protected]"Wednesday";

            break;

        case 5:

           [email protected]"Thursday";

            break;

        case 6:

           return  @"Friday";

            break;

        case 7:

           return  @"Saturday";

            break;

        case 1:

            [email protected]"Sunday";

            break;

        default:

            [email protected]"No Week";

            break;

    }

    // 用components,我們可以讀取其他更多的資料。

}

4. 用Get方式讀取網絡資料:

将網絡數讀取為字元串

- (NSString *) getDataByURL:(NSString *) url {

    return[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURLURLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]encoding:NSUTF8StringEncoding];

}

//讀取網絡圖檔

- (UIImage *) getImageByURL:(NSString *) url {

    return[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURLURLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];

}

多線程

[NSThread detachNewThreadSelector:@selector(scheduleTask)toTarget:self withObject:nil];

-(void) scheduleTask {

    //create a pool

   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //release thepool;

    [pool release];

}

//如果有參數,則這麼使用:

[NSThreaddetachNewThreadSelector:@selector(scheduleTask:) toTarget:selfwithObject:[NSDate date]];

-(void) scheduleTask:(NSDate *) mdate {

    //create a pool

   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //release thepool;

    [pool release];

}

//注意selector裡有冒号。

    //線上程裡運作主線程裡的方法

    [selfperformSelectorOnMainThread:@selector(moveToMain) withObject:nilwaitUntilDone:FALSE];

6. 定時器NSTimer用法:

代碼

  // 一個可以自動關閉的Alert視窗

    UIAlertView*alert = [[UIAlertView alloc] initWithTitle:nil

                                                    message:[@"一個可以自動關閉的Alert視窗"

                                                  delegate:nil

                                         cancelButtonTitle:nil //NSLocalizedString(@"OK",@"OK")   //取消任何按鈕

                                         otherButtonTitles:nil];

    //[alertsetBounds: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 theindicator 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);

    [indicatorstartAnimating];

    [alertinsertSubview:indicator atIndex:0];

    [indicatorrelease];

    [NSTimerscheduledTimerWithTimeInterval:3.0f

                                    target:self

                                  selector:@selector(dismissAlert:)

                                  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alert,

                  @"alert", @"testing ", @"key" ,nil]  //如果不用傳遞參數,那麼可以将此項設定為nil.

                                    repeats:NO];

   NSLog(@"release alert");

    [alertrelease];

-(void) dismissAlert:(NSTimer *)timer{

   NSLog(@"release timer");

    NSLog([[timeruserInfo] objectForKey:@"key"]);

    UIAlertView*alert = [[timer userInfo] objectForKey:@"alert"];

    [alertdismissWithClickedButtonIndex: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 %@",[languagesobjectAtIndex:0]); 

    //get the language& country code

    NSLocale*currentLocale = [NSLocale currentLocale];

   NSLog(@"Language Code is %@", [currentLocaleobjectForKey:NSLocaleLanguageCode]);

   NSLog(@"Country Code is %@", [currentLocaleobjectForKey:NSLocaleCountryCode

8. View之間切換的動态效果設定:

   SettingsController *settings = [[SettingsControlleralloc]initWithNibName:@"SettingsView" bundle:nil];

   settings.modalTransitionStyle =UIModalTransitionStyleFlipHorizontal;  //水準翻轉

    [selfpresentModalViewController:settings animated:YES];

    [settingsrelease];

9.NSScrollView 滑動用法:

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{

    NSLog(@"正在滑動中...");

}

//使用者直接滑動NSScrollView,可以看到滑動條

-(void) scrollViewDidEndDecelerating:(UIScrollView*)scrollView {

}

// 通過其他控件觸發NSScrollView滑動,看不到滑動條

- (void) scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView {

}

    11.鍵盤處理系列

 //set theUIKeyboard to switch to a different text field when you press return

//switch textField to the name of your textfield

[textField becomeFirstResponder];

srandom(time(NULL)); //随機數種子

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

   4. iPhone的系統目錄:

//得到Document目錄:

NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

//得到temp臨時目錄:

NSString *tempPath = NSTemporaryDirectory();

//得到目錄上的檔案位址:

NSString *檔案位址 = [目錄位址stringByAppendingPathComponent:@"檔案名.擴充名"];

 5. 狀态欄顯示Indicator:

[UIApplicationsharedApplication].networkActivityIndicatorVisible = YES;

  6.app Icon顯示數字:

- (void)applicationDidEnterBackground:(UIApplication*)application{

    [[UIApplicationsharedApplication] setApplicationIconBadgeNumber:5];

}

   7.sqlite儲存位址:

代碼

    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString*thePath = [paths objectAtIndex:0];

    NSString*filePath = [thePathstringByAppendingPathComponent:@"kilonet1.sqlite"];

    NSString*dbPath = [[[NSBundle mainBundle] resourcePath]

                       stringByAppendingPathComponent:@"kilonet2.sqlite"];

   8.Application退出:exit(0);

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

代碼

-(void) actionSheet :(UIActionSheet *) actionSheetdidDismissWithButtonIndex:(NSInteger) buttonIndex {

   NSLog(@"cancel actionSheet........");

    //當使用者按下cancel按鈕

    if( buttonIndex== [actionSheet cancelButtonIndex]) {

        exit(0);

    }

//    //當使用者按下destructive按鈕

//    if(buttonIndex == [actionSheet destructiveButtonIndex]) {

//        //DoSomething here.

//    }

}

- (void)alertView:(UIAlertView *)alertViewwillDismissWithButtonIndex:(NSInteger)buttonIndex {

    NSLog(@"cancel alertView........");

    if (buttonIndex== [alertView cancelButtonIndex]) {

        exit(0);

    }

}

  10.給Window設定全局的背景圖檔:

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

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

代碼

#pragma mark -

#pragma mark UITextFieldDelegate

//控制鍵盤跳轉

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (textField== _txtAccount) {

        if([_txtAccount.text length]==0) {

            returnNO;

        }

       [_txtPassword becomeFirstResponder];

    } else if(textField == _txtPassword) {

       [_txtPassword resignFirstResponder];

    }

    return YES;

}

//輸入框背景更換

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField{

    [textFieldsetBackground:[UIImage imageNamed:@"ctext_field_02.png"]];

    return YES;

}

-(void) textFieldDidEndEditing:(UITextField *)textField{

    [textFieldsetBackground:[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 設定滑動不超出本身範圍:

 [fcScrollViewsetBounces:NO];

 14. 在drawRect裡畫文字:

     UIFont * f =[UIFont systemFontOfSize:20];

    [[UIColordarkGrayColor] set];

    NSString * text= @"hi \nKiloNet";

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

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

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

array = [stringcomponentsSeparatedByString:@","];

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)])

{        [selfshowLogout];        return NO;    }   return YES;}

    18. 自定義View之間切換動畫:

代碼

- (void) pushController: (UIViewController*) controller

        withTransition: (UIViewAnimationTransition) transition

{

    [UIViewbeginAnimations:nil context:NULL];

    [selfpushViewController:controller animated:NO];

    [UIViewsetAnimationDuration:.5];

    [UIViewsetAnimationBeginsFromCurrentState:YES];

    [UIViewsetAnimationTransition:transition forView:self.view cache:YES];

    [UIViewcommitAnimations];

}

CATransition *transition = [CATransition animation];

transition.duration = kAnimationDuration;

transition.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut];

transition.type = kCATransitionPush;

transition.subtype = kCATransitionFromTop;

transitioning = YES;

transition.delegate = self;

[self.navigationController.view.layeraddAnimation:transition forKey:nil];

self.navigationController.navigationBarHidden = NO;

[self.navigationControllerpushViewController:tableViewController animated:YES];

     20.計算字元串長度:

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

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

1

 [[searchbar.subviewsobjectAtIndex:0]removeFromSuperview];

背景完全消除了,隻剩下搜尋框本身了。

  24.  圖像與緩存 :

UIImageView *wallpaper = [[UIImageView alloc]initWithImage:

        [UIImageimageNamed:@"icon.png"]]; // 會緩存圖檔

UIImageView *wallpaper = [[UIImageView alloc]initWithImage:

        [UIImageimageWithContentsOfFile:@"icon.png"]]; // 不會緩存圖檔

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

對圖層的操作:

(1.給圖層添加背景圖檔:

myView.layer.contents = (id)[UIImageimageNamed:@"view_BG.png"].CGImage;

(2.将圖層的邊框設定為圓腳

myWebView.layer.cornerRadius = 8;

myWebView.layer.masksToBounds = YES;

(3.給圖層添加一個有色邊框

myWebView.layer.borderWidth = 5;

myWebView.layer.borderColor = [[UIColor colorWithRed:0.52green:0.09 blue:0.07 alpha:1] CGColor];

将多個字元替換成空

NSCharacterSet *cs =[NSCharacterSet characterSetWithCharactersInString:@"1234567890|"];

NSString *resultstr = [[yourstrcomponentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

注:以上内容整理自網際網路,本人不對其準确性及版權負責。