您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發實用技巧大補帖:常用程式碼片段總整理

編輯:iOS 開發綜合

做 iOS 開發久了,會累積一些「用得到時一時想不起來」的小片段。以下把我在專案中常用到的技巧整理成一份備忘錄,涵蓋字串編碼、鍵盤、導航、動畫、多執行緒、檔案、UI 元件等各個層面。

字串與編碼

URL 編碼:

- (NSString *)URLEncodedString:(NSString *)string {
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(
        kCFAllocatorDefault, (CFStringRef)string, NULL,
        CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
    [result autorelease];
    return result;
}

產生 nonce(用 UUID 去掉了「-」)與 timestamp:

- (NSString *)generateNonce {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    NSMakeCollectable(theUUID);
    return [(NSString *)string stringByReplacingOccurrencesOfString:@"-" withString:@""];
}

- (NSString *)generateTimestamp {
    return [[NSString stringWithFormat:@"%d", time(NULL)] retain];
}

去除字串中的空格、tab 與換行:

NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *username = [mUsernameField stringValue];
username = [username stringByTrimmingCharactersInSet:whitespace];

鍵盤相關

iPhone 只有數字鍵盤(UIKeyboardTypeNumberPad、UIKeyboardTypePhonePad)支援改變顏色,設為 UIKeyboardAppearanceAlert 即可:

textField.keyboardAppearance = UIKeyboardAppearanceAlert;

在數字鍵盤上加一個 Done 按鈕(監聽鍵盤顯示通知,再把按鈕塞進鍵盤 view):

- (void)keyboardWillShow:(NSNotification *)note {
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    [doneButton setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];

    UIWindow *tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    for (int i = 0; i < [tempWindow.subviews count]; i++) {
        UIView *keyboard = [tempWindow.subviews objectAtIndex:i];
        if ([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) {
            [keyboard addSubview:doneButton];
        }
    }
}

導航與外觀

設定返回按鈕文字(在父層 viewController):

UIBarButtonItem *backbutton = [[UIBarButtonItem alloc] init];
backbutton.title = @"返回列表";
self.navigationItem.backBarButtonItem = backbutton;
[backbutton release];

防止螢幕自動鎖屏:

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

修改 UITableViewCell 選取時的背景:

UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;

動畫與畫面切換

用 beginAnimations 做圖片由左至右展開:

CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];
[myImageView setFrame:CGRectMake(0, 0, 310, 470)];
[UIView commitAnimations];

用 Core Animation 讓物件平移(需引入 QuartzCore.framework):

CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
theAnimation.duration = 1;
theAnimation.repeatCount = 2;
theAnimation.autoreverses = YES;
theAnimation.fromValue = [NSNumber numberWithFloat:0];
theAnimation.toValue = [NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];

多執行緒

// 建立背景執行緒
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];

// 背景方法
- (void)myMethod {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // 在背景執行的程式
    [pool release];
}

// 從背景回到主執行緒
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

擷取螢幕

UIGraphicsBeginImageContext(CGSizeMake(200, 400));
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(aImage);

UIImagePickerController 選圖與錄影

選圖重點在 sourceType(相簿、相機、已存相片)與 mediaTypes( image / movie)。選好後在 delegate 中依 mediaType 分別處理:

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:[self findUniqueSavePath] atomically:YES];
    } else if ([mediaType isEqualToString:@"public.movie"]) {
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *webData = [NSData dataWithContentsOfURL:videoURL];
        [webData writeToFile:[self findUniqueMoviePath] atomically:YES];
    }
    [picker dismissModalViewControllerAnimated:YES];
}

其他零散技巧

讓下層 view 也能接收觸碰:把上層的 userInteractionEnabled 設為 NO、下層設為 YES 並搭配 exclusiveTouch;用 tag 遍歷 subviews 找出特定檢視;用 UIWebView 的 stringByEvaluatingJavaScriptFromString: 從網頁抓資料;用 NSUserDefaults 或 plist 存放設定等。

這份整理偏向早期(MRC、UIWebView 時代)的寫法,適合作為觀念參考。若在新專案中實作,建議改用 ARC、WKWebView、Auto Layout、NSUserDefaults 的現代替代方案,並留意 Apple 已棄用的 API(如 UIAlertView、setIdleTimerDisabled 建議改用 isIdleTimerDisabled)。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved