iOS 開發總結 – iPhone手機開發技術文章 iPhone軟體開發教學課程

 

– (NSString *)URLEncodedString:(NSString *)string{

    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,

                                                       (CFStringRef)string,NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8);

    [result autorelease];

    return result;

}

 

//生成nonce

– (NSString *)generateNonce{

    CFUUIDRef theUUID = CFUUIDCreate(NULL);

    CFStringRef string = CFUUIDCreateString(NULL, theUUID);

    NSMakeCollectable(theUUID);

    return [(NSString *)string stringByReplacingOccurrencesOfString:@"-" withString:@""];

    //return (NSString *)string;

}

 

//生成Timestamp

– (NSString *)generateTimestamp{

    return [[NSString stringWithFormat:@"%d", time(NULL)] retain];

}

 

iPhone鍵盤改變顏色

隻有這2種數字鍵盤才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad

keyboardAppearance = UIKeyboardAppearanceAlert

代碼如下:

   NSArray *ws = [[UIApplication sharedApplication] windows];

    for(UIView *w in ws){

        NSArray *vs = [w subviews];

        for(UIView *v in vs){

            if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"]){

                v.backgroundColor = [UIColor redColor];

            }

        }

    }

從一個界面push到下一界面左上角返回按鈕文字設置

在父viewController中如下設置:

    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];

    backbutton.title = @"返回列表";

    self.navigationItem.backBarButtonItem = backbutton;

    [backbutton release];

 

navigationbar的back鍵觸發其他事件

UIButton *back =[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)];

[back addTarget:self action:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside];

[back setImage:[UIImage imageNamed:@"返回按鈕.png"] forState:UIControlStateNormal];

UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];

self.navigationItem.leftBarButtonItem = loginButtonItem

[back release];

[backButtonItem release];

防止屏幕暗掉鎖屏

 

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

 

將圖片從左到右翻頁效果顯示

   

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];

    [imageView setImage:[UIImage imageNamed:@"Bg.jpg"]];

    self.myImageView =imageView;

    [self.view addSubview:imageView];

    [imageView release];

    CGContextRef context = UIGraphicsGetCurrentContext();

    [UIView beginAnimations:nil context:context];

    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    [UIView setAnimationDuration:0.5];

    [myImageView setFrame:CGRectMake(0, 0, 310, 470)];   

    [UIView commitAnimations];

 

讓覆蓋在下面層的視圖接受觸摸事件

 

searchImage.exclusiveTouch = YES;//第一層

searchImage.userInteractionEnabled = NO;

myMapView.exclusiveTouch = NO;//第二層

myMapView.userInteractionEnabled = YES;

 

View的縮放

 

NSValue *touchPointValue = [[NSValue valueWithCGPoint:CGPointMake(100,100)] retain];

[UIView beginAnimations:nil context:touchPointValue];

transform = CGAffineTransformMakeScale(0.1,0.21);

firstPieceView.transform = transform;

[UIView commitAnimations];   

 

代碼循環添加按鈕,其他空間也可以用類似方法添加

 

– (void)viewDidLoad {

    [super viewDidLoad];

    for(int i = 0; i < 5; i++){

        CGRect frame;

        Btn[i] = [[UIButton buttonWithType:UIButtonTypeCustom] retain];

        [Btn[i] setImage:[UIImage imageNamed:@"Button.png"] forState:UIControlStateNormal];//設置按鈕圖片

        frame.size.width = 55;//設置按鈕坐標及大小

        frame.size.height = 84;

        frame.origin.x = (i%5)*57+5;

        frame.origin.y = 10;

        [Btn[i] setFrame:frame];

        [Btn[i] setBackgroundColor:[UIColor clearColor]];

        [Btn[i] addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:Btn[i]];

        [Btn[i] release];

    }

}

//響應按鈕事件

-(void)btnPressed:(id)sender{

    for(int i = 0; i < 5;i++){

        if([sender isEqual:Btn[i]]){

            NSLog(@"Btn[%d]:",i);

        }

    }

}

 

去除nsstring中的空格,table 以及newline,nextline

 

NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];

NSString *username = [mUsernameField stringValue];

username = [username stringByTrimmingCharactersInSet:whitespace];

 

UIImagePickerController

 

用UIImagePickerController選擇、顯示圖片或視頻,主要註意UIImagePickerController幾個屬性的設置

一:UI 顯示樣式,顯示的格式確定

1:sourceType

@property(nonatomic) UIImagePickerControllerSourceType sourceType

enum {

UIImagePickerControllerSourceTypePhotoLibrary,

UIImagePickerControllerSourceTypeCamera,

UIImagePickerControllerSourceTypeSavedPhotosAlbum

};

typedef NSUInteger UIImagePickerControllerSourceType;

sourceType用來確定用戶界面顯示的樣式:

共三種格式(模擬器上的效果圖)

UIImagePickerControllerSourceTypePhotoLibrary,

UIImagePickerControllerSourceTypeCamera,

 

 

UIImagePickerControllerSourceTypeSavedPhotosAlbum

 

為瞭區分是否支持視頻格式,一般要用到下面這個函數,以便確定mediaTypes。

+ (BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType

2:   mediaTypes

@property(nonatomic,copy) NSArray *mediaTypes

mediaTypes用來確定再picker裡顯示那些類型的多媒體文件,圖片?視頻?

+ (NSArray *)availableMediaTypesForSourceType:(UIImagePickerControllerSourceType)sourceType

二:選取動作處理

UIImagePickerControllerDelegate

通過代理來完成用戶在選中圖片,或者choose視頻時的處理方式:

 

共有三個可選的代理方法

– imagePickerController:didFinishPickingMediaWithInfo: 

– imagePickerControllerDidCancel: 

– imagePickerController:didFinishPickingImage:editingInfo:   Deprecated in iPhone OS 3.0

 

– (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

info中包括選取的照片,視頻的主要信息

NSString *const UIImagePickerControllerMediaType;         選取的類型 public.image  public.movie

NSString *const UIImagePickerControllerOriginalImage;    修改前的UIImage object.

NSString *const UIImagePickerControllerEditedImage;      修改後的UIImage object.

NSString *const UIImagePickerControllerCropRect; 原始圖片的尺寸NSValue object containing a CGRect data type

NSString *const UIImagePickerControllerMediaURL;          視頻在文件系統中 的 NSURL地址

保存視頻主要時通過獲取其NSURL 然後轉換成NSData

實例代碼如下:

 

– (void) pickImage: (id) sender

{

UIImagePickerController *ipc = [[UIImagePickerController alloc] init];

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){

     ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;

      ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];  

        } 

ipc.delegate = self;

ipc.allowsImageEditing = NO;

[self presentModalViewController:ipc animated:YES];

}

 

– (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

if ([mediaType isEqualToString:@"public.image"]){

// UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSLog(@"found an image");

[UIImageJPEGRepresentation(image, 1.0f) writeToFile:[self findUniqueSavePath] atomically:YES];

    SETIMAGE(image);

CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);

}

else if ([mediaType isEqualToString:@"public.movie"]){

 

NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

NSLog(@"found a video");

        NSData *webData = [NSData dataWithContentsOfURL:videoURL];

//NSData *video = [[NSString alloc] initWithContentsOfURL:videoURL];

[webData writeToFile:[self findUniqueMoviePath] atomically:YES];

CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);

// NSLog(videoURL);

}

[picker dismissModalViewControllerAnimated:YES];

}

 

UITextInputTraits屬性

 

 autocapitalizationType            設置鍵盤自動大小寫的屬性     UITextAutocapitalizationTypeNone

autocorrectionType  property  設置是否有自動修改提示   UITextAutocorrectionTypeNo

enablesReturnKeyAutomatically   Boolean值-設置在用戶沒有輸入是returnKey禁用,默認值NO

keyboardAppearance  設置鍵盤顯示方式  除瞭默認模式  還有一個UIKeyboardAppearanceAlert模式

keyboardType               設置鍵盤類型   UIKeyboardTypePhonePad 等

returnKeyType              設置renturnKey按鍵上的提示文字     UIReturnKeyGo   UIReturnKeyNext

secureTextEntry           BOOL值  -- 設置是否是密碼保護模式輸入

 

如下:

設置登錄用的 輸入框 UITextField

用戶名輸入框:

m_TF_username = [[UITextField alloc] initWithFrame:my_frame];

m_TF_username.borderStyle = UITextBorderStyleNone;

m_TF_username.clearButtonMode = UITextFieldViewModeWhileEditing;

m_TF_username.delegate = self;

m_TF_username.returnKeyType = UIReturnKeyNext;

m_TF_username.autocapitalizationType = UITextAutocapitalizationTypeNone;

[m_TF_username becomeFirstResponder];

密碼輸入框:

m_TF_password = [[UITextField alloc] initWithFrame:my_frame];

m_TF_password.borderStyle = UITextBorderStyleNone;

m_TF_password.clearButtonMode = UITextFieldViewModeWhileEditing;

m_TF_password.delegate = self;

m_TF_password.returnKeyType = UIReturnKeyGo;

m_TF_password.secureTextEntry =YES;

 

鍵盤透明

textField.keyboardAppearance = UIKeyboardAppearanceAlert;

 

狀態欄的網絡活動風火輪是否旋轉

[UIApplication sharedApplication].networkActivityIndicatorVisible,默認值是NO。

 

截取屏幕圖片

//創建一個基於位圖的圖形上下文並指定大小為CGSizeMake(200,400)

UIGraphicsBeginImageContext(CGSizeMake(200,400));

 

//renderInContext 呈現接受者及其子范圍到指定的上下文

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

  

 //返回一個基於當前圖形上下文的圖片

 UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();

 

 //移除棧頂的基於當前位圖的圖形上下文

UIGraphicsEndImageContext();

 

//以png格式返回指定圖片的數據

imageData = UIImagePNGRepresentation(aImage);

 

 

更改cell選中的背景

    UIView *myview = [[UIView alloc] init];

    myview.frame = CGRectMake(0, 0, 320, 47);

    myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];

    cell.selectedBackgroundView = myview;

 

在數字鍵盤上添加button:

//定義一個消息中心

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:註冊一個觀察員 name:消息名稱

– (void)keyboardWillShow:(NSNotification *)note {

    // create custom button

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

   

    // locate keyboard view

    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回應用程序window

    UIView* keyboard;

    for(int i=0; i<[tempWindow.subviews count]; i++) //遍歷window上的所有subview

    {

        keyboard = [tempWindow.subviews objectAtIndex:i];

        // keyboard view found; add the custom button to it

        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)

        [keyboard addSubview:doneButton];

    }

}

 

正則表達式使用:

被用於正則表達式的字串必須是可變長的,不然會出問題

 

將一個空間放在視圖之上

[scrollView insertSubview:searchButton aboveSubview:scrollView];

 

從本地加載圖片

NSString *boundle = [[NSBundle mainBundle] resourcePath];

[web1 loadHTMLString:[NSString stringWithFormat:@"<img src=http://up.aiwalls.com/2012/1214/20121214044003551.com/&'/>"] baseURL:[NSURL fileURLWithPath:boundle]];

 

從網頁加載圖片並讓圖片在規定長寬中縮小

[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='http://fei263.blog.163.com/blog/%@' height='90px' width='90px'></body></html>",goodsInfo.GoodsImg] baseURL:nil];

將網頁加載到webview上通過javascript獲取裡面的數據,如果隻是發送瞭一個連接請求獲取到源碼以後可以用正則表達式進行獲取數據

NSString *javaScript1 = @"document.getElementsByName('.u').item(0).value";

NSString *javaScript2 = @"document.getElementsByName('.challenge').item(0).value";

NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];

NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];

 

用NSString怎麼把UTF8轉換成unicode

utf8Str //

NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];

 

View自己調用自己的方法:

[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黃色段為方法名,和延遲幾秒執行.

 

顯示圖像:

CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);

UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];

[myImage setImage:[UIImage imageNamed:@"myImage.png"]];

myImage.opaque = YES; //opaque是否透明

[self.view addSubview:myImage];

[myImage release];

 

WebView:

CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);

UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];

[webView setBackgroundColor:[UIColor whiteColor]];

NSString *urlAddress = @"http://www.google.com";

NSURL *url = [NSURL URLWithString:urlAddress];

NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[webView loadRequest:requestObj];

[self addSubview:webView];

[webView release];

 

顯示網絡活動狀態指示符

這是在iPhone左上部的狀態欄顯示的轉動的圖標指示有背景發生網絡的活動。

UIApplication* app = [UIApplication sharedApplication];

app.networkActivityIndicatorVisible = YES;

 

動畫:一個接一個地顯示一系列的圖象

NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImage imageNamed:@"myImage2.png"], [UIImage imageNamed:@"myImage3.png"], [UIImage imageNamed:@"myImage4.gif"], nil];

UIImageView *myAnimatedView = [UIImageView alloc];

[myAnimatedView initWithFrame:[self bounds]];

myAnimatedView.animationImages = myImages; //animationImages屬性返回一個存放動畫圖片的數組

myAnimatedView.animationDuration = 0.25; //瀏覽整個圖片一次所用的時間

myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 動畫重復次數

[myAnimatedView startAnimating];

[self addSubview:myAnimatedView];

[myAnimatedView release];

 

動畫:顯示瞭something在屏幕上移動。註:這種類型的動畫是“開始後不處理” -你不能獲取任何有關物體在動畫中的信息(如當前的位置) 。如果您需要此信息,您會手動使用定時器去調整動畫的X和Y坐標

這個需要導入QuartzCore.framework

CABasicAnimation *theAnimation;

theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];

//Creates and returns an CAPropertyAnimation instance for the specified key path.

//parameter:the key path of the property to be animated

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"];

 

Draggable items//拖動項目

Here's how to create a simple draggable image.//這是如何生成一個簡單的拖動圖象

1. Create a new class that inherits from UIImageView

@interface myDraggableImage : UIImageView { }

2. In the implementation for this new class, add the 2 methods:

– (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event

{

// Retrieve the touch point 檢索接觸點

CGPoint pt = [[touches anyObject] locationInView:self];

startLocation = pt;

[[self superview] bringSubviewToFront:self];

}

– (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event

{

// Move relative to the original touch point 相對以前的觸摸點進行移動

CGPoint pt = [[touches anyObject] locationInView:self];

CGRect frame = [self frame];

frame.origin.x += pt.x – startLocation.x;

frame.origin.y += pt.y – startLocation.y;

[self setFrame:frame];

}

3. Now instantiate the new class as you would any other new image and add it to your view

//實例這個新的類,放到你需要新的圖片放到你的視圖上

dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];

[dragger setImage:[UIImage imageNamed:@"myImage.png"]];

[dragger setUserInteractionEnabled:YES];

 

線程:

1. Create the new thread:

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

2. Create the method that is called by the new thread:

– (void)myMethod

{

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

*** code that should be run in the new thread goes here ***

[pool release];

}

//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.

[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

 

Plist files

Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.

// Look in Documents for an existing plist file

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

NSString *documentsDirectory = [paths objectAtIndex:0];

myPlistPath = [documentsDirectory stringByAppendingPathComponent:

[NSString stringWithFormat: @"%@.plist", plistName] ];

[myPlistPath retain];

// If it's not there, copy it from the bundle

NSFileManager *fileManger = [NSFileManager defaultManager];

if ( ![fileManger fileExistsAtPath:myPlistPath] )

{

NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];

}

//Now read the plist file from Documents

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

NSString *documentsDirectoryPath = [paths objectAtIndex:0];

NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];

NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];

//Now read and set key/values

myKey = (int)[[plist valueForKey:@"myKey"] intValue];

myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];

[plist setValue:myKey forKey:@"myKey"];

[plist writeToFile:path atomically:YES];

 

Alerts

Show a simple alert with OK button.

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

@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];

[alert release];

 

Info button

Increase the touchable area on the Info button, so it's easier to press.

CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);

[infoButton setFrame:newInfoButtonRect];

 

Detecting Subviews

You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.

for (UIImageView *anImage in [self.view subviews])

{

if (anImage.tag == 1)

        { // do something }

}

發佈留言