轉 聽說是iOS開發一年總結的筆記,有空看看 iphone開發筆記 退回輸入鍵盤 - (BOOL) textFieldShouldReturn:(id)textField{ [textField resignFirstResponder]; } CGRect CGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形 NSStringFromCGRect(someCG) 把CGRect結構轉變爲格式化字符串; CGRectFromString(aString) 由字符串恢復出矩形; CGRectInset(aRect) 建立較小或較大的矩形(中心點相同),+較小 -較大 CGRectIntersectsRect(rect1, rect2) 判斷兩矩形是否交叉,是否重疊 CGRectZero 高度和寬度爲零的/位於(0,0)的矩形常量 CGPoint & CGSize CGPoint aPoint = CGPointMake(x, y); CGSize aSize = CGSizeMake(width, height); 設置透明度 [myView setAlpha:value]; (0.0 < value < 1.0) 設置背景色 [myView setBackgroundColor:[UIColor redColor]]; (blackColor;darkGrayColor;lightGrayColor; whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor; magentaColor;orangeColor;purpleColor; brownColor; clearColor; ) 自定義顏色 UIColor *newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float) alpha:(float)]; 0.0~1.0 豎屏 320X480 橫屏 480X320 狀態欄高 (顯示時間和網絡狀態) 20 像素 導航欄、工具欄高(返回) 44像素 隱藏狀態欄 [[UIApplication shareApplication] setStatusBarHidden: YES animated:NO] 橫屏 [[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight]. 屏幕變更檢測 orientation == UIInterfaceOrientationLandscapeLeft 全屏 window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds]; 自動適應父視圖大小: aView.autoresizingSubviews = YES; aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); 定義按鈕 UIButton *scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal]; scaleUpButton.frame = CGRectMake(40, 420, 100, 40); [scaleUpButton addTarget:self action:@selector(scaleUp) forControlEvents:UIControlEventTouchUpInside]; 設置視圖背景圖片 UIImageView *aView; [aView setImage:[UIImage imageNamed:@」name.png」]]; view1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"image1.png"]]; 自定義UISlider的樣式和滑塊 咱們使用的是UISlider的setMinimumTrackImage,和setMaximumTrackImage方法來定義圖片的,這兩個方法能夠設置滑塊左邊和右邊的圖片的,不過若是用的是同一張圖片且寬度和控件寬度基本一致,就不會有變形拉伸的後果,先看代碼,寫在 viewDidLoad中: //左右軌的圖片 UIImage *stetchLeftTrack= [UIImage imageNamed:@"brightness_bar.png"]; UIImage *stetchRightTrack = [UIImage imageNamed:@"brightness_bar.png"]; //滑塊圖片 UIImage *thumbImage = [UIImage imageNamed:@"mark.png"]; UISlider *sliderA=[[UISlider alloc]initWithFrame:CGRectMake(30, 320, 257, 7)]; sliderA.backgroundColor = [UIColor clearColor]; sliderA.value=1.0; sliderA.minimumValue=0.7; sliderA.maximumValue=1.0; [sliderA setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal]; [sliderA setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal]; //注意這裏要加UIControlStateHightlighted的狀態,不然當拖動滑塊時滑塊將變成原生的控件 [sliderA setThumbImage:thumbImage forState:UIControlStateHighlighted]; [sliderA setThumbImage:thumbImage forState:UIControlStateNormal]; //滑塊拖動時的事件 [sliderA addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged]; //滑動拖動後的事件 [sliderA addTarget:self action:@selector(sliderDragUp:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:sliderA]; 爲了你們實驗方便,我附上背景圖brightness_bar.png和滑塊圖mark.png http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png -(IBAction)sliderValueChanged:(id)sender{ UISlider *slider = (UISlider *) sender; NSString *newText = [[NSString alloc] initWithFormat:@」%d」, (int)(slider.value + 0.5f)]; label.text = newText; } 活動表單 <UIActionSheetDelegate> - (IBActive) someButtonPressed:(id) sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@」Are you sure?」 delegate:self cancelButtonTitle:@」No way!」 destructiveButtonTitle:@」Yes, I’m Sure!」 otherButtonTitles:nil]; [actionSheet showInView:self.view]; [actionSheet release]; } 警告視圖 <UIAlertViewDelegate> - (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex { if(buttonIndex != [actionSheet cancelButtonIndex]) { NSString *message = [[NSString alloc] initWithFormat:@」You can breathe easy, everything went OK.」]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@」Something was done」 message:message delegate:self cancelButtonTitle:@」OK」 otherButtonTitles:nil]; [alert show]; [alert release]; [message release]; } } 動畫效果 -(void)doChange:(id)sender { if(view2 == nil) { [self loadSec]; } [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1]; [UIView setAnimationTransition:([view1 superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.view cache:YES]; if([view1 superview]!= nil) { [view1 removeFromSuperview]; [self.view addSubview:view2]; }else { [view2 removeFromSuperview]; [self.view addSubview:view1]; } [UIView commitAnimations]; } Table View <UITableViewDateSource> #pragma mark - #pragma mark Table View Data Source Methods //指定分區中的行數,默認爲1 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.listData count]; } //設置每一行cell顯示的內容 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIndentifier = @"SimpleTableIndentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIndentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIndentifier] autorelease]; } UIImage *image = [UIImage imageNamed:@"13.gif"]; cell.imageView.image = image; NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row]; cell.textLabel.font = [UIFont boldSystemFontOfSize:20]; if(row < 5) cell.detailTextLabel.text = @"Best friends"; else cell.detailTextLabel.text = @"friends"; return cell; } 圖像、文本標籤和詳細文本標籤 圖像:若是設置圖像,則它顯示在文本的左側; 文本標籤:這是單元的主要文本(UITableViewCellStyleDefault 只顯示文本標籤);詳細文本標籤:這是單元的輔助文本,一般用做解釋性說明或標籤 UITableViewCellStyleSubtitle UITableViewCellStyleDefault UITableViewCellStyleValue1 UITableViewCellStyleValue2 <UITableViewDelegate> #pragma mark - #pragma mark Table View Delegate Methods //把每一行縮進級別設置爲其行號 - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; return row; } //獲取傳遞過來的indexPath值 - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; if (row == 0) return nil; return indexPath; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; NSString *rowValue = [listData objectAtIndex:row]; NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",rowValue]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Row Selected" message:message delegate:nil cancelButtonTitle:@"Yes, I did!" otherButtonTitles:nil]; [alert show]; [alert release]; [message release]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } //設置行的高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 40; } NavigationController 推出push 推出pop [self.navigationController pushViewController:_detailController animated:YES]; [self.navigationController popViewControllerAnimated:YES]; Debug: NSLog(@"%s %d", __FUNCTION__, __LINE__); 點擊textField外的地方回收鍵盤 先定義一個UIControl類型的對象,在上面能夠添加觸發事件,令SEL實踐爲回收鍵盤的方法,最後將UIControl的實例加到當前View上。 UIControl *m_control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [m_control addTarget:self action:@selector(keyboardReturn) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:m_control]; - (void) keyboardReturn { [aTextField resignFirstResponder]; } 鍵盤覆蓋輸入框 當鍵盤調出時將輸入框覆蓋時,能夠用下方法: - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { [self.view setFrame:CGRectMake(0, -100, 320, 480) ]; return YES; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { [self.view setFrame:CGRectMake(0, 0, 320, 480)]; return YES; } 當準備輸入時,將視圖的位置上調100,這樣鍵盤就不能覆蓋到輸入框。 當依賴注入方法很差使時,能夠在AppDelegate內申明一個全局的控制器實例_anotherViewController,在另外一個須要使用_anotherViewController的地方定義如下委託方法,使用共享的UIApplication實例來獲取該委託的引用 SomeAppDelegate *appDelegate = (SomeAppDelegate *)[[UIApplication sharedApplication] delegate]; _anotherViewController = appDelegate._anotherViewController; UIViewController內建Table View 純代碼在UIViewController控制器內建Table View @interface RootViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { NSArray *timeZoneNames; } @property (nonatomic,retain) NSArray *timeZoneNames; @end (void) loadView { UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] style: UITableViewStylePlain]; tableView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingWidth); tableView.delegate = self; tableView.dataSource = self; [tableView reloadData]; self.view = tableView; [tableView release]; } 將plist文件中的數據賦給數組 NSString *thePath = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"]; NSArray *array = [NSArray arrayWithContentsOfFile:thePath]; UITouch 手指的觸摸範圍:64X64 #pragma mark - #pragma mark Touch Events - (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event { originFrame = bookCover.frame; NSLog(@"%s %d", __FUNCTION__,__LINE__); if ([touches count] == 2) { NSArray *twoTouches = [touches allObjects]; UITouch *firstTouch = [twoTouches objectAtIndex:0]; UITouch *secondTouch = [twoTouches objectAtIndex:1]; CGPoint firstPoint = [firstTouch locationInView:bookCover]; CGPoint secondPoint = [secondTouch locationInView:bookCover]; CGFloat deltaX = secondPoint.x - firstPoint.x; CGFloat deltaY = secondPoint.y - firstPoint.y; initialDistance = sqrt(deltaX * deltaX + deltaY * deltaY ); frameX = bookCover.frame.origin.x; frameY = bookCover.frame.origin.y; frameW = bookCover.frame.size.width; frameH = bookCover.frame.size.height; NSLog(@"%s %d", __FUNCTION__,__LINE__); } } - (void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event { if([touches count] == 2) { NSLog(@"%s %d", __FUNCTION__,__LINE__); NSArray *twoTouches = [touches allObjects]; UITouch *firstTouch = [twoTouches objectAtIndex:0]; UITouch *secondTouch = [twoTouches objectAtIndex:1]; CGPoint firstPoint = [firstTouch locationInView:bookCover]; CGPoint secondPoint = [secondTouch locationInView:bookCover]; CGFloat deltaX = secondPoint.x - firstPoint.x; CGFloat deltaY = secondPoint.y - firstPoint.y; CGFloat currentDistance = sqrt(deltaX * deltaX + deltaY * deltaY ); if (initialDistance == 0) { initialDistance = currentDistance; } else if (currentDistance != initialDistance) { CGFloat changedDistance = currentDistance - initialDistance; NSLog(@"changedDistance = %f",changedDistance); [bookCover setFrame:CGRectMake(frameX - changedDistance / 2, frameY - (changedDistance * frameH) / (2 * frameW), frameW + changedDistance, frameH + (changedDistance * frameH) / frameW)]; } } } - (void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event { UITouch *touch = [touches anyObject]; UITouch雙擊圖片變大/還原 if ([touch tapCount] == 2) { NSLog(@"%s %d", __FUNCTION__,__LINE__); if (!flag) { [bookCover setFrame:CGRectMake(bookCover.frame.origin.x - bookCover.frame.size.width / 2, bookCover.frame.origin.y - bookCover.frame.size.height / 2, 2 * bookCover.frame.size.width, 2 * bookCover.frame.size.height)]; flag = YES; } else { [bookCover setFrame:CGRectMake(bookCover.frame.origin.x + bookCover.frame.size.width / 4, bookCover.frame.origin.y + bookCover.frame.size.height / 4, bookCover.frame.size.width / 2, bookCover.frame.size.height / 2)]; flag = NO; } } } Get the Location of Touches (CGPoint)locationInView:(UIView *)view (CGPoint)previousLocationInView:(UIView *)view view window Getting Touch Attributes tapCount(read only) timestamp(read only) phase(read only) Getting a Touch Object's Gesture Recognizers gestureRecognizers Touch Phase UITouchPhaseBegan UITouchPhaseMoved UITouchPhaseStationary UITouchPhaseEnded UITouchPhaseCancelled 從Plist裏讀內容 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"]; NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath]; NSString *book = [dictionary objectForKey:bookTitle]; [textView setText:book]; (void) initialize { NSUserDefaults = [NSUserDefaults standardUserDefaults]; NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"YES" forKey:@"DeleteBackup"]; [defaults registerDefaults:appDefaults]; } To get a value of a default, use the valueForKey: method: [[theDefaultsController values] valueForKey:@"userName"]; To set a value for a default, use setValue:forKey: [[theDefaultsController values] setValue:newUserName forKey:@"userName"]; [[NSUserDefaults standardUserDefaults] setValue:aVale forKey:aKey]; [[NSUserDefaults standardUserDefaults] valueForKey:aKey]; 獲取Documents目錄 NSArray *paths = NSSearchPathForDictionariesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"theFile.txt"]; 獲取tmp目錄 NSString *tempPath = NSTemporaryDirectory(); NSString *tempFile = [tempPath stringByAppendingPathComponent:@"tempFile.txt"]; [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"someKey"]; [[NSUserDefaults standardUserDefaults] objectForKey:aKey]; 自定義NavigationBar navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; [navigationBar setBarStyle:UIBarStyleBlackOpaque]; myNavigationItem = [[UINavigationItem alloc] initWithTitle:@"Setting"]; [navigationBar setItems:[NSArray arrayWithObject:myNavigationItem]]; [self.view addSubview:navigationBar]; backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)]; myNavigationItem.leftBarButtonItem = backButton; 利用Safari打開一個連接 NSURL *url = [NSURL URLWithString:@"http://www.cnblogs.com/tracy-e/"]; [[UIApplication sharedApplication] openURL:url]; 利用UIWebView顯示pdf文件、網頁。。。 webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [webView setDelegate:self]; [webView setScalesPageToFit:YES]; [webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; [webView setAllowsInlineMediaPlayback:YES]; [self.view addSubview:webView]; NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"ojc" ofType:@"pdf"]; NSURL *url = [NSURL fileURLWithPath:pdfPath]; NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5]; [webView loadRequest:request]; [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: @"http://www.cnblogs.com/tracy-e/"]]]; NSString *errorString = [NSString stringWithFormat:@"<html><center><font size= +5 color ='red'>An Error Occurred:<br>%@</fone></center></html>",error]; [myWebView loadHTMLString:errorString baseURL:nil]; //Stopping a load request when the view is to disappear - (void)viewWillDisappear:(BOOL)animate{ if ([myWebView loading]){ [myWebView stopLoading]; } myWebView.delegate = nil; [UIApplication shareApplication].networkActivityIndicatorVisible = NO; } 漢字轉碼 NSString *oriString = @"\u67aa\u738b"; NSString *escapedString = [oriString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; Checking for background support on earlier versions of iOS UIDevice *device = [UIDevice currentDevice]; BOOL backgroundSupported = NO; if ([device respondsToSelector:@selector(isMultitaskingSupported)]){ backgroundSupported = device.multitaskingSupported; } Being a Responsible,Multitasking-Aware Application # Do not make any OpenGL ES calls from your code. # Cancel any Bonjour-related services before being suspended. # Be prepared to handle connection failures in your network-based sockets. # Save your application state before moving to the background. # Release any unneeded memory when moving to the background. # Stop using shared system resources before being suspended. # Avoid updating your windows and views. # Respond to connect and disconnect notification for external accessories. # Clean up resource for active alerts when moving to the background. # Remove sensitive information from views before moving to the background. # Do minimal work while running in the background. Handing the Keyboard notifications //Call this method somewhere in your view controller setup code - (void) registerForKeyboardNotifications{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil]; } //Called when the UIKeyboardDidShowNotification is sent - (void)keyboardWasShown:(NSNotification *) aNotification{ if(keyboardShown) return; NSDictionary *info = [aNotification userInfo]; //get the size of the keyboard. NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyboardSize = [aValue CGRectValue].size; //Resize the scroll view CGRect viewFrame = [scrollView frame]; viewFrame.size.height -= keyboardSize.height; //Scroll the active text field into view CGRect textFieldRect = [activeField frame]; [scrollView scrollRectToVisible:textFieldRect animated:YES]; keyboardShown = YES; } //Called when the UIKeyboardDidHideNotification is sent - (void)keyboardWasHidden:(NSNotification *) aNotification{ NSDictionary *info = [aNotification userInfo]; //Get the size of the keyboard. NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; CGSize keyboardSize = [aValue CGRectValue].size; //Reset the height of the scroll view to its original value CGRect viewFrame = [scrollView Frame]; viewFrame.size.height += keyboardSize.height; scrollView.frame = viewFrame; keyboardShown = NO; } 點擊鍵盤的next按鈕,在不一樣的textField之間換行 //首先給不一樣的textField賦不一樣的且相鄰的tag值 - (BOOL)textFieldShouldReturn:(UITextField *)textField { if ([textField returnKeyType] != UIReturnKeyDone) { NSInteger nextTag = [textField tag] + 1; UIView *nextTextField = [[self tableView] viewWithTag:nextTag]; [nextTextField becomeFirstResponder]; } else { [textField resignFirstResponder]; } return YES; } Configuring a date formatter - (void)viewDidLoad { [super viewDidLoad]; dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setGeneratesCalendarDates:YES]; [dateFormatter setLocale:[NSLocale currentLocale]]; [dateFormatter setCalendar:[NSCalendar autoupdatingCurrentCalendar]]; [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; DOB.placeholder = [NSString stringWithFormat:@"Example: %@",[dateFormatter stringFromDate:[NSDate date]]]; } - (void)textFieldDidEndEditing:(UITextField *)textField{ [textField resignFirstResponder]; if ([textField.text isEqualToString:@""]) return; switch (textField.tag){ case DOBField: NSDate *theDate = [dateFormatter dateFromString:textField.text]; if (theDate) [inputDate setObject:theDate forKey:MyAppPersonDOBKey]; break; default: break; } } tableView的cell高度 tableView的cell高度除了在delegate中指定外,還能夠在任意位置以[tableView setRowHeight:44]的方式指定 [[self navigationItem] setLeftBarButtonItem:[self editButtonItem]]; - (void)setEditing:(BOOL)editing animated:(BOOL)animated{ [super setEditing:editing animated:animated]; if (editing){ ...... } else{ ...... } } One added a subview to a view, release the subview to avoid the extra retain count of it, Because when you insert a view as a subview using addSubview:, the subview is retained by its superview. When you remove the subview from its superview using the removeFromSuperview: method, subview is autoreleased. 爲UINavigationBar設置背景圖片 在iPhone開發中, 有時候咱們想給導航條添加背景圖片, 實現多樣化的導航條效果, 用其餘方法每每沒法達到理想的效果, 通過網上搜索及屢次實驗, 肯定以下最佳實現方案: 爲UINavigatonBar增長以下Category(類別:提供一種爲某個類添加方法而又沒必要編寫子類的途徑,類別只能添加成員函數,不能添加數據成員): @implementation UINavigationBar (CustomImage) - (void)drawRect:(CGRect)rect { UIImage *image = [UIImage imageNamed: @"NavigationBar.png"]; [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; } @end 例如, 在個人項目中, 添加以下代碼: ///////////////////////////////////////////////////////// /* input: The image and a tag to later identify the view */ @implementation UINavigationBar (CustomImage) - (void)drawRect:(CGRect)rect { UIImage *image = [UIImage imageNamed: @"title_bg.png"]; [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; } @end ///////////////////////////////////////////////////////// @implementation FriendsPageViewController // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { self.navigationBar.tintColor = [UIColor purpleColor]; [self initWithRootViewController:[[RegPageViewController alloc] init]]; [super viewDidLoad]; } ...... 實現的效果以下圖: 轉載,原文地址 http://blog.csdn.net/wave_1102/archive/2009/11/04/4768212.aspx 爲UINavigationBar添加自定義背景 @implementation UINavigationBar (UINavigationBarCategory) - (void)drawRect:(CGRect)rect { //顏色填充 // UIColor *color = [UIColor redColor]; // CGContextRef context = UIGraphicsGetCurrentContext(); // CGContextSetFillColor(context, CGColorGetComponents( [color CGColor])); // CGContextFillRect(context, rect); // self.tintColor = color; //圖片填充 UIColor *color = [UIColor colorWithRed:46.0f/255.0f green:87.0f/255.0f blue:29.0f/255.0f alpha:1.0f]; UIImage *img = [UIImage imageNamed: @"bg.png"]; [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; self.tintColor = color; } @end 加載圖片要及時release 你還在使用myImage = [UIImage imageNamed:@"icon.png"]; 嗎? 如題,是否是你們爲了方便都這樣加載圖片啊 myImage = [UIImage imageNamed:@"icon.png"]; 那麼當心了 這種方法在一些圖片不多,或者圖片很小的程序裏是ok的。 可是,在大量加載圖片的程序裏,請千萬不要這樣作。 爲何呢 ??????? 這種方法在application bundle的頂層文件夾尋找由供應的名字的圖象。 若是找到圖片,裝載到iPhone系統緩存圖象。那意味圖片是(理論上)放在內存裏做爲cache的。 試想你圖片多了,是什麼後果? 圖片cache極有可能不會響應 memory warnings and release its objects 因此,用圖片的時候必定要當心的alloc和release。 推薦使用 NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"]; myImage = [UIImage imageWithContentsOfFile:path]; // Todo use of myImage [myImage release]; From: http://www.cocoachina.com/bbs/simple/?t27420.html uiwebview打開doc,pdf文件 UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 55, 320, 300)]; webView.delegate = self; webView.multipleTouchEnabled = YES; webView.scalesPageToFit = YES; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *docPath = [documentsDirectory stringByAppendingString:@"/doc2003_1.doc"]; NSLog(@"#######%@",docPath); NSURL *url = [NSURL fileURLWithPath:docPath]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; [self.view addSubview:webView]; [webView release]; From:http://blog.csdn.net/dadalan/archive/2010/10/22/5959301.aspx iPhone遊戲中既播放背景音樂又播放特效聲音的辦法 有時候在 iPhone 遊戲中,既要播放背景音樂,同時又要播放好比槍的開火音效。此時您能夠試試如下方法 NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"]; //建立音樂文件路徑 NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath]; AVAudioPlayer* musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil]; [musicURL release]; [musicPlayer prepareToPlay]; //[musicPlayer setVolume:1]; //設置音量大小 //musicPlayer .numberOfLoops = -1;//設置音樂播放次數 -1爲一直循環 要導入框架 AVFoundation.framework,頭文件中 #import <AVFoundation/AVFoundation.h>;作成類的話則更方便。 From: http://blog.csdn.net/dadalan/archive/2010/10/19/5950493.aspx NSNotificationCenter用於增長回調函數 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_willBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; UINavigationBar 背景Hack LOGO_320×44.png 圖片顯示在背景上, @implementation UINavigationBar (UINavigationBarCategory) - (void)drawRect:(CGRect)rect { //加入旋轉座標系代碼 // Drawing code UIImage *navBarImage = [UIImage imageNamed:@"LOGO_320×44.png"]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 0.0, self.frame.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGPoint center=self.center; CGImageRef cgImage= CGImageCreateWithImageInRect(navBarImage.CGImage, CGRectMake(0, 0, 1, 44)); CGContextDrawImage(context, CGRectMake(center.x-160-80, 0, 80, self.frame.size.height), cgImage); CGContextDrawImage(context, CGRectMake(center.x-160, 0, 320, self.frame.size.height), navBarImage.CGImage); CGContextDrawImage(context, CGRectMake(center.x+160, 0, 80, self.frame.size.height), cgImage); } @end old code CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), navBarImage.CGImage); hack 過logo 再也不拉伸 From: http://blog.163.com/fengyi1103@126/blog/static/13835627420106279102671/ 清除電話號碼中的其餘符號(源碼) 最近從通信錄讀取電話號碼,讀出得號碼如:134-1814-****。 而我須要的爲11位純數字,一直找方法解決此問題,今天終於找到了。。 分享一下…… 代碼以下: NSString *originalString = @"(123) 123123 abc"; NSMutableString *strippedString = [NSMutableString stringWithCapacity:originalString.length]; NSScanner *scanner = [NSScanner scannerWithString:originalString]; NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; while ([scanner isAtEnd] == NO) { NSString *buffer; if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) { [strippedString appendString:buffer]; } // --------- Add the following to get out of endless loop else { [scanner setScanLocation:([scanner scanLocation] + 1)]; } // --------- End of addition } NSLog(@"%@", strippedString); // "123123123" From: http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring 正則判斷:字符串只包含字母和數字 NSString *mystring = @"Letter1234"; NSString *regex = @"[a-z][A-Z][0-9]"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; if ([predicate evaluateWithObject:mystring] == YES) { //implement } 一行代碼設置 UITableViewCell 與導航條間距 UITableView 的 cell 默認出如今 uitableview 的第一行,若是你想自定義 UITableViewCell 與導航條間距的話,可使用下面這行代碼 tableview.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)]autorelease]; From: http://blog.163.com/fengyi1103@126/blog/static/1383562742010101611107492/ 修改 UITableview 滾動條顏色的方法 UITableview 的滾動條默認顏色是黑色的,若是 UItableview 背景也是深顏色,則滾動條會變的很不明顯。您能夠用下面這行代碼來改變滾動條的顏色 self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite; 固然,最後的 「White」 也能夠換成其它顏色。 下文件以前獲取到文件大小的代碼 下面這段代碼,能實如今下載文件以前得到文件大小,應用在軟件裏,能在很大程度上改善用戶體驗 [m_pASIHTTPRequest setDidReceiveResponseHeadersSelector:@selector(didReceiveResponseHeaders:)]; - (void)didReceiveResponseHeaders:(ASIHTTPRequest *)request { NSLog(@"didReceiveResponseHeaders %@",[m_request.responseHeaders valueForKey:@"Content-Length"]); } 網絡編程總結 iphone 一:確認網絡環境3G/WIFI 1. 添加源文件和framework 開發Web等網絡應用程序的時候,須要確認網絡環境,鏈接狀況等信息。若是沒有處理它們,是不會經過Apple的審(咱們的)查的。 Apple 的 例程 Reachability 中介紹了取得/檢測網絡狀態的方法。要在應用程序程序中使用Reachability,首先要完成以下兩部: 1.1. 添加源文件: 在你的程序中使用 Reachability 只須將該例程中的 Reachability.h 和 Reachability.m 拷貝到你的工程中。以下圖: 1.2.添加framework: 將SystemConfiguration.framework 添加進工程。以下圖: 2. 網絡狀態 Reachability.h中定義了三種網絡狀態: typedef enum { NotReachable = 0, //無鏈接 ReachableViaWiFi, //使用3G/GPRS網絡 ReachableViaWWAN //使用WiFi網絡 } NetworkStatus; 所以能夠這樣檢查網絡狀態: Reachability *r = [Reachability reachabilityWithHostName:@「www.apple.com」]; switch ([r currentReachabilityStatus]) { case NotReachable: // 沒有網絡鏈接 break; case ReachableViaWWAN: // 使用3G網絡 break; case ReachableViaWiFi: // 使用WiFi網絡 break; } 3.檢查當前網絡環境 程序啓動時,若是想檢測可用的網絡環境,能夠像這樣 // 是否wifi + (BOOL) IsEnableWIFI { return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); } // 是否3G + (BOOL) IsEnable3G { return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); } 例子: - (void)viewWillAppear:(BOOL)animated { if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) && ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) { self.navigationItem.hidesBackButton = YES; [self.navigationItem setLeftBarButtonItem:nil animated:NO]; } } 4. 連接狀態的實時通知 網絡鏈接狀態的實時檢查,通知在網絡應用中也是十分必要的。接續狀態發生變化時,須要及時地通知用戶: Reachability 1.5版本 // My.AppDelegate.h #import "Reachability.h" @interface MyAppDelegate : NSObject <UIApplicationDelegate> { NetworkStatus remoteHostStatus; } @property NetworkStatus remoteHostStatus; @end // My.AppDelegate.m #import "MyAppDelegate.h" @implementation MyAppDelegate @synthesize remoteHostStatus; // 更新網絡狀態 - (void)updateStatus { self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus]; } // 通知網絡狀態 - (void)reachabilityChanged:(NSNotification *)note { [self updateStatus]; if (self.remoteHostStatus == NotReachable) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"AppName", nil) message:NSLocalizedString (@"NotReachable", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; [alert release]; } } // 程序啓動器,啓動網絡監視 - (void)applicationDidFinishLaunching:(UIApplication *)application { // 設置網絡檢測的站點 [[Reachability sharedReachability] setHostName:@"www.apple.com"]; [[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES]; // 設置網絡狀態變化時的通知函數 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:@"kNetworkReachabilityChangedNotification" object:nil]; [self updateStatus]; } - (void)dealloc { // 刪除通知對象 [[NSNotificationCenter defaultCenter] removeObserver:self]; [window release]; [super dealloc]; } Reachability 2.0版本 // MyAppDelegate.h @class Reachability; @interface MyAppDelegate : NSObject <UIApplicationDelegate> { Reachability *hostReach; } @end // MyAppDelegate.m - (void)reachabilityChanged:(NSNotification *)note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); NetworkStatus status = [curReach currentReachabilityStatus]; if (status == NotReachable) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName"" message:@"NotReachable" delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil]; [alert show]; [alert release]; } } - (void)applicationDidFinishLaunching:(UIApplication *)application { // ... // 監測網絡狀況 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain]; hostReach startNotifer]; // ... } 二:使用NSConnection下載數據 1.建立NSConnection對象,設置委託對象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]]; [NSURLConnection connectionWithRequest:request delegate:self]; 2. NSURLConnection delegate委託方法 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; - (void)connectionDidFinishLoading:(NSURLConnection *)connection; 3. 實現委託方法 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // store data [self.receivedData setLength:0]; //一般在這裏先清空接受數據的緩存 } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { /* appends the new data to the received data */ [self.receivedData appendData:data]; //可能屢次收到數據,把新的數據添加在現有數據最後 } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // 錯誤處理 } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // disconnect [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; NSLog(returnString); [self urlLoaded:[self urlString] data:self.receivedData]; firstTimeDownloaded = YES; }