天天看點

iphone開發之常用代碼:不斷更新

1,擷取翻轉事件,并開啟翻轉:

隻要在viewcontroller的類中加入

iphone開發之常用代碼:不斷更新
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{

//翻轉後要執行的代碼

return YES;

}      
iphone開發之常用代碼:不斷更新

2,-(void)viewWillAppear:(BOOL)animated,- (void)viewDidLoad 的差別。

viewwillappear是每次視圖控制器的視圖出現前執行的代碼。而viewdidload是每次視圖控制器載入是執行的代碼。

比如說:當a視圖控制器的視圖第一次出現是兩個都要執行,但當a被push後有pop回來時,隻有viewwillappear執行。

3,如何讓視圖始終跟着手指移動,并有反彈事件

xsum=photopositon.origin.x+photopositon.size.width/2-touchstart.x;

ysum=photopositon.origin.y+photopositon.size.height/2-touchstart.y;

currentview.center=CGPointMake(xsum+p.x, ysum+p.y);

if (pow(currentview.center.x-160,2.0)>pow(photopositon.size.width/2,2.0)||

pow(currentview.center.y-240,2.0)>pow(photopositon.size.height/2, 2.0)) 

{

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

[UIView setAnimationDuration:0.3];

currentview.center=CGPointMake(160, 240);

[UIView commitAnimations];

}

就是讓currentview的視圖中心始終與手指保持一定的方位。

4,控制導覽列和toolbar

[self.navigationController   ...]

[self.navigationController.toolbar  ...]

比如說讓他們都消失:

[self.navigationController setToolbarItems:NULL animated:YES];

[self.navigationController.toolbar setBarStyle:UIBarStyleBlackTranslucent];

[self.navigationController setToolbarHidden:NO animated:YES];

5,自定義控件事件:

addTarget:self action:@selector(....) forControlEvents:....

比如擷取某個按鈕的觸摸事件;

[new addTarget:self action:@selector(onChooseItem:) forControlEvents:UIControlEventTouchUpInside]

則當按鈕按下時,- (void)onChooseItem:(id) sender 就會被調用。

sender傳的就是被按下按鈕的指針。

6.擷取檔案的路徑,即擷取documents的路徑

//擷取檔案路徑
    NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath=[path objectAtIndex:0];

NSLog(@"%@",documentsPath);      

補充:

iphone開發之常用代碼:不斷更新
1. NSSearchPathForDirectoriesInDomains和NSHomeDirectory
    iPhone和symbian 3rd一樣,會為每一個應用程式生成一個私有目錄,這個目錄位于/Users/sundfsun2009/Library/Application Support/iPhone         Simulator/User/Applications下,并随即生成一個數字字母串作為目錄名,在每一次應用程式啟動時,這個字母數字串都是不同于上一次。

    通常使用Documents目錄進行資料持久化的儲存,而這個Documents目錄可以通過 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserdomainMask,YES) 得到,代碼如下:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

   // NSString *path = [documentsDirectory stringByAppendingPathComponent:@"aa.plist"];

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

    列印結果如下:

    path:   /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7/Documents

    而這個目錄還可以通過 NSHomeDirectory()來得到,代碼如下:

    NSString *destPath = NSHomeDirectory();
    NSLog(@"path:   %@",destPath);
    //destPath = [destPath stringByAppendingPathComponent: @"Documents"];
    //NSString *xmlpath = [destPath stringByAppendingPathComponent: @"menu/menu.xml"];

    列印結果如下:

    path:   /Users/apple/Library/Application Support/iPhone Simulator/4.2/Applications/6F4BC466-C5D6-440C-BAAC-BE20FA468C61

    看看兩者列印出來的結果,我們可以看出這兩種方法的不同。

2. 浏覽document下所有圖檔資源

    #define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
    NSArray *fileList = [[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER]
                pathsMatchingExtensions:[NSArray arrayWithObject:@"png"]] ;

3. 得到圖檔中的某一部分:

    UIImage *image = [UIImage imageNamed:filename];
    CGImageRef imageRef = image.CGImage;

    CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);

    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);

    UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];      
iphone開發之常用代碼:不斷更新

7.在documents的路徑下建立檔案。

首先要擷取documents的路徑,如上第6條。

其次就是下面的語句了:

NSString *writePath=[NSString stringWithFormat:@"%@/%@.txt",documentsPath,@"aaa"];
NSData *data = [@"" dataUsingEncoding:NSUTF8StringEncoding];//新檔案的初始資料,設為空
[[NSFileManager defaultManager] createFileAtPath:writePath contents:data attributes:nil];//建立檔案的指令在這裡      

這樣就可以在documents檔案夾下建立一個aaa.txt的檔案了。哈哈哈哈哈。

或者是用下面的語句,

NSString *writePath=[NSString stringWithFormat:@"%@/%@.txt",documentsDirectory,@"bbb"];
NSError *error;
[@"fasdfasdasddaa" writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:&error];      

這樣就可以在documents檔案夾下建立一個bbb.txt的檔案了。并且,檔案中的有"fasdfasdasddaa"字元。

總結起來就是,先給要存儲的東西取一個名字,然後,找到它的路徑。然後以這個名字建立。建立的時候可以添加内容。

當然,圖檔也可以批量的生成,假如說讓你把一張圖檔複制500遍,并且給他按照(1-500)重命名。

你可以用上面的方法,用一個循環批量的生成500張圖檔。

iphone開發之常用代碼:不斷更新
UIImage *image = [UIImage imageNamed:@"240*360.png"];
    NSData *data = UIImagePNGRepresentation(image);
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSMutableArray *muArray;
    NSString *filePath = nil;
    for (int j = 1; j<=500; j++) {
        filePath = [[NSString alloc] initWithFormat:@"%@/%d.png",documentPath,j];
        [data writeToFile:filePath atomically:YES];
        NSString *newPath = [[NSString alloc] initWithFormat:@"%@",documentPath];
        muArray = [[NSMutableArray alloc] initWithContentsOfFile:newPath];
        [muArray addObject:filePath];
        [filePath release];      
iphone開發之常用代碼:不斷更新

7.iphone開發中随機數的産生。

iphone開發之常用代碼:不斷更新
// Get random number between 0 and 99 
int x = arc4random() % 81; 
// Get random number between 500 and 999 
int y = ((arc4random()%501)+500);

NSLog(@"0--99之間的随機數%d",x);
NSLog(@"500--999之間的随機數%d",y);      
iphone開發之常用代碼:不斷更新

8.好看的文字處理

以tableView中cell的textLabel為例子:

iphone開發之常用代碼:不斷更新
cell.backgroundColor  = [UIColor scrollViewTexturedBackgroundColor];
    //設定文字的字型
    cell.textLabel.font = [UIFont fontWithName:@"American Typewriter" size:100.0f];
    //設定文字的顔色
    cell.textLabel.textColor = [UIColor orangeColor];
    //設定文字的背景顔色
    cell.textLabel.shadowColor = [UIColor whiteColor];
    //設定文字的顯示位置
    cell.textLabel.textAlignment = UITextAlignmentCenter;      
iphone開發之常用代碼:不斷更新

9.新手學習webview

iphone開發之常用代碼:不斷更新
//Web view
//A basic UIWebView. 

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開發之常用代碼:不斷更新

10。———————-隐藏Status Bar—————————–

讀者可能知道一個簡易的方法,那就是在程式的viewDidLoad中加入

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];      

11.更改AlertView背景   

 UIAlertView *theAlert = [[[UIAlertViewalloc] initWithTitle:@"Atention"

                                                        message: @"I'm a Chinese!"

                                                       delegate:nil 

                                              cancelButtonTitle:@"Cancel" 

                                              otherButtonTitles:@"Okay",nil] autorelease];

    [theAlert show];

    UIImage *theImage = [UIImage imageNamed:@"loveChina.png"];    

    theImage = [theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];

    CGSize theSize = [theAlert frame].size;

    UIGraphicsBeginImageContext(theSize);    

    [theImage drawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)]; //這個地方的大小要自己調整,以适應alertview的背景顔色的大小。

    theImage = UIGraphicsGetImageFromCurrentImageContext();    

    UIGraphicsEndImageContext();

    theAlert.layer.contents = (id)[theImage CGImage];

12。iOS背景播放聲音  

AVAudioSession *session = [AVAudioSession sharedInstance];  

    [session setActive:YES error:nil];  

    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

13。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

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://fei263.blog.163.com/blog/0001.png'/>"] 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 } 

}

16.

//UILabel 和字型大小的比對,可以用到制作電子書的時候。

iphone開發之常用代碼:不斷更新
//UILabel 和字型大小的比對,可以用到制作電子書的時候。
    NSString *str = @"UILabel 和字型大小的比對.親愛的,在一起的日子很平淡,似乎波瀾不驚,隻是,這種平凡的日子是最浪漫的,對嗎?遇到你之前,世界像一片荒草原;遇到你之後,世界像一個遊樂園。過去的許多歲月,對我來說像一縷輕煙,未來的無限生涯,因你而幸福無邊。愛一個人是在夜裡等待另一個人的呼吸,雖然隔着千裡萬裡,但我知道你在手機的那一端,于是我便會夜夜等待.守株待兔是人間最大的幸福,因為我有目标,你就是我要逮那隻兔子,是我一生要好好照顧保護那個人.沒有你的時候,你就是我的世界;和你在一起時,世界就是你的。親愛的,情人節快樂。";
    UIFont *font = [UIFont fontWithName:@"Arial" size:36.0f];
    CGSize size = CGSizeMake(320, 2000);
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];//先設為“0”的大小狀态
    label.numberOfLines = 0;//當設為0的時候,label顯示多行。
    
    CGSize labelSize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];//得到size的寬和高
    NSLog(@"%f",labelSize.height);
    label.frame = CGRectMake(0, 0, labelSize.width, labelSize.height);
    label.text = str;
    label.font = font;
    label.textColor = [UIColor blueColor];
    [self.view addSubview:label];
    
    [label release];      
iphone開發之常用代碼:不斷更新

17.選中某一行的時候,該行顔色變化

[tableView deselectRowAtIndexPath:indexPath animated:NO];//選擇目前行,使得改行顔色變化,選中後的反顯顔色即刻消失。

18.ios 音頻背景播放

在按Home的情況下,背景如何播放音樂?

在Info.plist增加一項 Required backgroound modes默然是數組,在其下增加一個元素App plays audio

之後在代碼中添加:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
[[AVAudioSession sharedInstance] setActive:YES error: nil];      

或者是下面的代碼:

AVAudioSession *session = [AVAudioSession sharedInstance];  
        [session setActive:YES error:nil];  
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];11:47:36      

放到初始化的中或在播放音樂前的即可。

19。數組排序

iphone開發之常用代碼:不斷更新
for (int j=0;j<[arr count];j++)
    {
        for (int i=0; i<[arr count]-1-j; i++) {
            if ([[arr objectAtIndex:i] intValue]>[[arr objectAtIndex:i+1] intValue]) {
                aa = [arr objectAtIndex:i+1];
                [arr replaceObjectAtIndex:i+1 withObject:[arr objectAtIndex:i]];
                [arr replaceObjectAtIndex:i withObject:aa];
                
            }
        }
    }


或者這樣。。。。。。。。

//對數組進行排序
-(void)paixuForArray:(NSMutableArray *)_array
{
    NSString *aa;
    for (int j=0;j<[_array count];j++)
    {
        for (int i=0; i<[_array count]-1-j; i++) {
            if ([[[_array objectAtIndex:i] substringWithRange:NSMakeRange(3, 4)] intValue]<[[[_array objectAtIndex:i+1] substringWithRange:NSMakeRange(3, 4)] intValue]) {
                aa = [_array objectAtIndex:i+1];
                [_array replaceObjectAtIndex:i+1 withObject:[_array objectAtIndex:i]];
                [_array replaceObjectAtIndex:i withObject:aa];
                
            }
        }
    }
    
}



      
iphone開發之常用代碼:不斷更新

20。擷取目前的日期,時間,星期幾

iphone開發之常用代碼:不斷更新
NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    
    // 年月日獲得
    comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
                        fromDate:date];
    NSInteger year = [comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSLog(@"year: %d month: %d, day: %d", year, month, day);
    
    
    //目前的時分秒獲得
    comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
                        fromDate:date];
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    NSInteger second = [comps second];
    NSLog(@"hour: %d minute: %d second: %d", hour, minute, second);
    
    // 周幾和星期幾獲得
    comps = [calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
                        fromDate:date];
    NSInteger week = [comps week]; // 今年的第幾周
    NSInteger weekday = [comps weekday]; // 星期幾(注意,周日是“1”,周一是“2”。。。。)
    NSInteger weekdayOrdinal = [comps weekdayOrdinal]; // 這個月的第幾周
    NSLog(@"week: %d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);


參考相關文章介紹,下面兩篇文章介紹的很像細。
http://www.2cto.com/kf/201202/118985.html
http://www.cppblog.com/walkklookk/archive/2011/09/15/155852.aspx


      
iphone開發之常用代碼:不斷更新

21。

iPhone随機數

求随機數的三種方法:

1.    srand((unsigned)time(0));

        int i = rand() % 5;      

2.    srandom(time(0));

        int i = random() % 5;

3.    int i = arc4random() % 5 (常用) ;

參考:

http://www.cocoachina.com/bbs/read.php?tid=70719&keyword=%CB%E6%BB%FA%CA%FD

http://www.cocoachina.com/bbs/read.php?tid-2977-fpage-2-toread--page-1.html

http://www.codeios.com/thread-310-1-1.html

ios程式設計:iPhone How-to:給導航欄貼圖

時間:2011-04-22 csdn部落格 林家男孩  

通過tintColor屬性可以定制UINavigationBar的背景顔色,但如果需要設定漸變色、甚至紋理來說,就需要貼圖了。 比較“暴力”的一種做法就是通過Category來重新實作- (void) drawRect:(CGRect)rect的實作,“暴力”是因為這種殺傷面很廣,所有項目内的UINavigationBar都會是以改變。這點在應 用中應該格外小心。

@interface UINavigationBar (ImageBackground) 
@end 
@implementation UINavigationBar (ImageBackground) 
- (void) drawRect:(CGRect)rect { 
    [[UIImage imageNamed:@"bkimage.png"] drawInRect:rect]; 
} 
@end      

來源:http://blog.csdn.net/lbj05/archive/2011/04/02/6297218.aspx