你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iPhone開發中的技巧整理(二)

iPhone開發中的技巧整理(二)

編輯:IOS開發綜合
1、NSCalendar用法  -(NSString *) getWeek:(NSDate *)d { NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit; NSDateComponents *components = [calendar components:units fromDate:d]; [calendar release]; switch ([components weekday]) { case1: return @"Monday"; break; case2: return @"Tuesday"; break; case3: return @"Wednesday"; break; case4: return @"Thursday"; break; case5: return @"Friday"; break; case6: return @"Saturday"; break; case7: return @"Sunday"; break; default: return @"NO Week"; break; } NSLog(@"%@",components);  }   2、將網絡數據讀取為字符串 -(NSString *)getDataByURL:(NSString *)url { return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding]; }   3、讀取⺴絡圖⽚ -(UIImage *)getImageByURL:(NSString *)url { return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; }   4、多線程(這種方式,只管建立線程,不管回收線程) [NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil]; -(void)scheduleTask { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [pool release];  }   如果有參數,則這麼⽤ [NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]]; -(void)scheduleTask:(NSDate *)mdate { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [pool release]; }   在線程⾥運⾏主線程⾥的⽅法 [self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];   5、⽤戶缺省值NSUserDefaults讀取: NSUserDefaults *df = [NSUserDefaults standardUserDefaults]; NSArray *languages = [df objectForKey:@"AppleLanguages"];  NSLog(@"all language is %@",languages); NSLog(@"index is %@",[languages objectAtIndex:0]); NSLocale *currentLocale = [NSLocale currentLocale]; NSLog(@"language Code is %@",[currentLocale objectForKey:NSLocaleLanguageCode]);  NSLog(@"Country Code is %@",[currentLocale objectForKey:NSLocaleCountryCode]);   6、view之間轉換的動態效果設置 SecondViewController *secondViewController = [[SecondViewController alloc] init]; secondViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//⽔水平翻轉 [self.navigationController presentModalViewController:secondViewController animated:YES]; [secondViewController release];     7、UIScrollView 滑動用法: -(void)scrollViewDidScroll:(UIScrollView *)scrollView { NSLog(@"正在滑動中。。") } //⽤戶直接滑動UIScrollView,可以看到滑動條 -(void)scrollViewDidEndDelerating:(UIScrollView *)scrollView { } //通過其他控件觸發UIScrollView滑動,看不到滑動條 -(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { } //UIScrollView 設置滑動不超出本⾝身范圍 [scrollView setBounces:NO];    8、iphone的系統目錄: //得到Document:目錄 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; //得到temp臨時目錄 NSString *temPath = NSTemporaryDirectory(); //得到目錄上的文件地址 NSString *address = [paths stringByAppendingPathComponent:@"1.rtf"];   9、狀態欄顯⽰示indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;   10、app Icon顯示數字: - (void)applicationDidEnterBackground:(UIApplication *)application {    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:5]; } 11、sqlite保存地址: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMask, YES); NSString *thePath = [paths objectAtIndex:0]; NSString *filePath = [thePath stringByAppendingPathComponent:@"kilometer.sqlite"]; NSString *dbPath = [[[NSBundle mainBundle] resourcePathstringByAppendingPathComponent:@"kilometer2.sqlite"];   12、鍵盤彈出隱藏,textfield變位置 _tspasswordTF = [[UITextField alloc] initWithFrame: CGRectMake(100, 150, 260, 30)]; _tspasswordTF.backgroundColor = [UIColor redColor]; _tspasswordTF.tag = 2; /* Use this method to release shared resources, save user data, _tspasswordTF.delegate = self; [self.window addSubview: _tspasswordTF];   - (void)textFieldDidBeginEditing:(UITextField *)textField { [self animateTextField: textField up: YES];  }   - (BOOL)textFieldShouldReturn:(UITextField *)textField { [self animateTextField: textField up: NO];  [textField resignFirstResponder]; return YES; } - (void) animateTextField: (UITextField*) textField up: (BOOL) up { const int movementDistance = 80;  // tweak as needed  const float movementDuration = 0.3f;  // tweak as needed int movement = (up ? -movementDistance : movementDistance); [UIView beginAnimations: nil context: nil]; [UIView setAnimationBeginsFromCurrentState: YES]; [UIView setAnimationDuration: movementDuration]; self.window.frame = CGRectOffset(self.window.frame, 0, movement); [UIView commitAnimations];  }   13、獲取圖片的尺⼨ CGImageRef img = [imageView.image CGImage];  NSLog(@"%d",CGImageGetWidth(img));  NSLog(@"%d",CGImageGetHeight(img));   14、AlertView,ActionSheet的cancelButton點擊事件: - (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex; // before animation and hiding view {   NSLog(@"cancel alertView... buttonindex = %d",buttonIndex); //當⽤用戶按下Cancel按鈕   if (buttonIndex == [alertView cancelButtonIndex]){   exit(0);    } } - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex { NSLog(@"%s %d button = %d cancel actionSheet.....",__FUNCTION__,__LINE__, buttonIndex); //當⽤用戶按下Cancel按鈕   if (buttonIndex == [actionSheet cancelButtonIndex]) {   exit(0);   }  } 15、給window設置全局背景圖片 self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@""]];   16、tabcontroller隨意切換tabbar -(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController  或者 -(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 或者 _tabBarController.selectedIndex = tabIndex;   17、計算字符串⻓度: CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size: 18]].width;   18、計算點到線段的最短距離 根據結果坐標使⽤用CLLocation類的函數計算實際距離。 double x1, y1, x2, y2, x3, y3; double px =x2 -x1; double py = y2 -y1; double som = px *px + py *py; double u =((x3 - x1)*px +(y3 - y1)*py)/som; if(u > 1) { u=1; } if (u < 0) { u =0; } //the closest point double x = x1 + u *px; double y = y1 + u * py; double dx = x - x3; double dy = y - y3; double dist = sqrt(dx*dx + dy*dy);   19、UISearchBar背景透明  在使用UISearchBar時,將背景⾊設定為clearColor,或者將translucent設為YES,都 不能使背景透明,經過一番研究,發現了一種超級簡單和實用的⽅法: [[searchbar.subviews objectAtIndex:0] removeFromSuperview]; 背景完全消除了,只剩下搜索框本身了。   20、圖像與緩存 : UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"icon.png"]]; // 會緩存圖片 UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不會緩存圖⽚片   21、iphone對視圖層的操作 // 將textView的邊框設置為圓角 _textView.layer.cornerRadius = 8; _textView.layer.masksToBounds = YES; //給textView添加一個有色邊框 _textView.layer.borderWidth = 5; _textView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];  //textView添加背景圖片 _textView.layer.contents = (id)[UIImage imageNamed:@"31"].CGImage;   22、關閉當前應用 [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];   23、給iPhone程序添加歡迎界面 1、將你需要的歡迎界面的圖片,存成Default.png  [NSThread sleepForTimeInterval:10.0]; 這樣歡迎頁面就停留10秒後消失了。   24、NSString NSDate轉換 NSString* myString= @"testing"; NSData* data=[myString dataUsingEncoding: [NSString defaultCStringEncodi ng]]; NSString* aStr = [[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding];   25、UIWebView中的dataDetectorTypes  如果你希望在浏覽頁面時,頁面上的電話號碼顯示成鏈接形式,點擊電話號碼就撥打電話,這時你就需要用到dataDetectorTypes了。   NSURL *url = [NSURL URLWithString:@"http://2015.iteye.com"];  NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; webView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;  [webView loadRequest:requestObj];   26、打開蘋果電腦浏覽器的代碼 如您想在 Mac 軟件中集成一鍵打開浏覽器功能,可以使用以下代碼   [[NSWorkspace sharedWorkspace] openURLs: urls withAppBundleIdentifier:@"com.apple.Safari" options: NSWorkspaceLaunchDefault additionalEventParamDescriptor: NULL launchIdentifiers: NULL];   27、設置StatusBar以及NavigationBar的樣式 [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque; self.navigationController.navigationBar.barStyle = UIBarStyleBlack;   28、隱藏Status Bar 你可能知道一個簡易的方法,那就是在程序的viewDidLoad中加入以下代碼:   [UIApplication sharedApplication].statusBarHidden = YES;  此法可以隱藏狀態條,但問題在於,狀態條所占空間依然無法為程序所用。 本篇介紹的方法依然簡單,但更為奏效。通過簡單的3個步驟,在plist中加入一 個鍵值來實現。 1. 點擊程序的Info.plist 2. 右鍵點擊任意一處,選擇Add Row 3. 加入的新鍵值,命名為UIStatusBarHidden或者Status bar is initially hidden,然後選上這一項。   29、產生隨機數的最佳方案 arc4random()會返回一個整型數,因此,返回1至100的隨機數可以這樣寫:  arc4random()%100 + 1;   30、string 和char轉換  NSString *cocoaString = [[NSString alloc] initWithString:@"MyString"]; const char *myCstring = [cocoaString cString]; const char *cString = "Hello"; NSString *cocoString = [[NSString alloc] initWithCString:cString];   31、用UIWebView在當前程序中打開網頁 如果URL中帶中文的話,必須將URL中的中文轉成URL形式的才行。 NSString *query = [NSString stringWithFormat:@"http://www.baidu.com?q=蘋 果"]; NSString *strUrl = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strUrl]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];  [webView loadRequest:requestObj];   32、阻止ios設備鎖屏  [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; 或  [UIApplication sharedApplication].idleTimerDisabled = YES;    33、一條命令卸載Xcode和 iPhone SDK sudo /Developer/Library/uninstall-devtools --mode=all   34、獲取按鈕的title -(void)btnPressed:(id)sender { NSString *title = [sender titleForState:UIControlStateNormal];  NSString *newText = [[NSString alloc] initWithFormat:@"%@",title];  label.text = newText; [newText release];  }   35、NSDate to NSString NSString *dateStr = [[NSString alloc] initWithFormat:@"%@", date]; 或者 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSString *strDate = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"%@", strDate);  [dateFormatter release];   36、圖片由小到大緩慢顯示的效果 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; [imageView setImage:[UIImage imageNamed:@"4.jpg"]];  self.ANImageView = imageView; [self.view addSubview:imageView]; [imageView release]; CGContextRef context = UIGraphicsGetCurrentContext();  [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  [UIView setAnimationDuration:2.5]; CGImageRef img = [self.ANImageView.image CGImage]; [ANImageView setFrame:CGRectMake(0, 0, CGImageGetWidth(img), CGImageGetHeight(img))]; [UIView commitAnimations];  NSLog(@"%lu",CGImageGetWidth(img)); NSLog(@"%lu",CGImageGetHeight(img));   37、數字轉字符串 NSString *newText = [[NSString alloc] initWithFormat:@"%d",number];  numberlabel.text = newText; [newText release];   38、隨機函數arc4random() 的使用. 在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的 最大值則是 0x100000000 (4294967296),從而有更好的精度。使用 arc4random()還不需要生成隨機種子,因為第一次調用的時候就會自動生成。 如: arc4random() 來獲取0到100之間浮點數 #define ARC4RANDOM_MAX 0x100000000 double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f); 1. self.view.backgroundColor = [UIColor colorWithHue: arc4random() % 2 55 / 255 2. 3. 4. saturation: arc4random() % 2 brightness: arc4random() % 2 alpha: 1.0];   39、改變鍵盤顏色的實現 iPhone和iPod touch的鍵盤顏色其實是可以通過代碼更改的,這樣能更匹配 App的界面風格,下面是改變iPhone鍵盤顏⾊色的代碼。 -(void)textFieldDidBeginEditing:(UITextField *)textField { 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:@"UIPeripheralHostView"]) { v.backgroundColor = [UIColor blueColor]; } } } } 55 / 255 55 / 255 _textField.keyboardAppearance = UIKeyboardAppearanceAlert;//有這個設置屬性 才起作用   40、iPhone上實現Default.png動畫 添加一張和Default.png⼀一樣的圖片,對這個圖片進行動畫,從而實現Default動畫的漸變消 失的效果。 UIImageView *splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; splashView.image = [UIImage imageNamed:@"Default.png"]; [self.window addSubview:splashView]; [self.window bringSubviewToFront:splashView]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:2.0]; [UIView setAnimationTransition:UIViewAnimationTransitionNone forView: self.window cache:YES]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:cont ext:)]; splashView.alpha = 0.0; splashView.frame = CGRectMake(-60, -85, 440, 635);  [UIView commitAnimations];   41、將EGO主題色添加到xcode中 打開終端,執行以下命令 Shell代碼 1. mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; 2. cd ~/Library/Application\ Support/Xcode/Color\ Themes; 3. curl -O http://developers.enormego.com/assets/egotheme/ EGO.xccolortheme 然後,重啟Xcode,選擇Preferences > Fonts & Colors,最後從Color Theme 中選擇EGO即可。   42、將圖片保存到圖片庫中 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject];  if ([touch tapCount]== 1) { UIImageWriteToSavedPhotosAlbum([ANImageView image], nil, nil, nil); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存儲照⽚片 message:@"您已將照⽚存於圖片庫中,打開照片程序即可查" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];   [alert show]; [alert release]; }  }   43、讀取plist文件 //取得文件路徑 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"文件 名" ofType:@"plist"]; //讀取到一個字典 NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath]; //讀取到一個數組 NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];   44、使用#pragma mark 加上這樣的標識後,在導航條上會顯示源文件上方法列表,這樣就可對功能相關的方法進行分隔,方便查看了。 設置UITabBarController默認的啟動Item //a tabBar UITabBarController *tabBarController = [[UITabBarController alloc] init]; NSArray *controllers = [NSArray arrayWithObjects: nav1, nav2, nav3, nav4, nil]; tabBarController.viewControllers = controllers; tabBarController.selectedViewController = nav2;   45、NSUserDefaults的使用 NSUserDefaults *store = [NSUserDefaults standardUserDefaults];  NSUInteger selectedIndex = 1; [store setInteger:selectedIndex forKey:@"selectedIndex"]; if ([store valueForKey:@"selectedIndex"] != nil) { NSInteger index = [store integerForKey:@"selectedIndex"];  NSLog(@"⽤用戶已經設置的selectedIndex的值是:%d", index); }  else {  NSLog(@"請設置默認的值"); }   46、更改Xcode的缺省公司名 在終端中執行以下命令: defaults write com.apple.Xcode PBXCustomTemplateMacroDefiniti ons '{"ORGANIZATIONNAME" = "COMPANY";}'   47、設置uiView,成圓角矩形 畫個圓角的矩形沒啥難的,有兩種方法: 1 。直接修改view的樣式,系統提供好的了: view.layer.cornerRadius = 6; view.layer.masksToBounds = YES; 用layer做就可以了,十分簡單。這個需要倒庫 QuartzCore.framework; 2. 在view 裡面畫圓角矩形 CGFloat radius = 20.0; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1); CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect); CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy = CGRectGetMaxY(rect); CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClosePath(context); CGContextDrawPath(context, kCGPathFill); 用畫筆的方法,在drawRect裡面做。   48、畫圖時圖片倒轉解決方法 CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1, -1); drawImage = [UIImage imageNamed:@"12.jpg"]; CGImageRef image = CGImageRetain(drawImage.CGImage); CGContextDrawImage(context, CGRectMake(30.0, 200, 450, 695), image); CGContextRestoreGState(context);   49、Nsstring 自適應文本寬高度 CGSize feelSize = [feeling sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(190, 200)]; float feelHeight = feelSize.height;   50、用HTTP協議,獲取www.baidu.com網站的HTML數據: [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"]];   51、viewDidLoad中設置按鈕圖案 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(0, 0, 60, 30); [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button];   UIImage *buttonImageNormal = [UIImage imageNamed:@"huifu-001.png"]; UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];  [button setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; UIImage *buttonImagePressed = [UIImage imageNamed:@"qyanbuhuifu-001.png"]; UIImage *stretchableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];  [button setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted]; 52、鍵盤上的return鍵改成Done: textField.returnKeyType = UIReturnKeyDone;   53、textfield設置成為密碼框: [textField_pwd setSecureTextEntry:YES];   54、收回鍵盤: [textField resignFirstResponder]; 或者 [textfield addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditin gDidEndOnExit]; 55、振動: #import<AudioToolbox/AudioToolbox.h> //需加頭文件 方法一: AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); 方法二: AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 當設備不支持方法一函數時,起蜂鳴作用, 而方法二支持所有設備   56、用Cocoa刪除文件: NSFileManager *defaultManager = [NSFileManager defaultManager];  [defaultManager removeFileAtPath: tildeFilename  handler: nil];   57、UIView透明漸變與移動效果: //動畫配制開始 [UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:2.5]; //圖片上升動畫 CGRect rect = imgView.frame ; rect.origin.y = 30; imgView.frame = rect; //半透明度漸變動畫 imgView.alpha = 0; //提交動畫 [UIView commitAnimations];   58、在UIView的drawRect方法內,用Quartz2D API繪制一個像素寬的水平直線:  -(void)drawRect:(CGRect)rect{ //獲取圖形上下文 CGContextRef context = UIGraphicsGetCurrentContext(); //設置圖形上下文的路徑繪制顏色 CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); //取消防鋸齒 CGContextSetAllowsAntialiasing(context, NO); //添加線 CGContextMoveToPoint(context, 50, 50);  CGContextAddLineToPoint(context, 100, 50); //繪制 CGContextDrawPath(context, kCGPathStroke); }   59、用UIWebView加載: www.baidu.com UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [web loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.baidu.com"]]]; [self.view addSubview:web];  [web release];   60、利用UIImageView實現動畫: - (void)viewDidLoad { [super viewDidLoad]; UIImageView *fishAni=[[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; [self.view addSubview:fishAni];  [fishAni release]; //設置動畫幀 fishAni.animationImages=[NSArray arrayWithObjects: [UIImage imageNamed:@"1.jpg"], [UIImage imageNamed:@"2.jpg"], [UIImage imageNamed:@"3.jpg"], [UIImage imageNamed:@"4.jpg"], [UIImage imageNamed:@"5.jpg"],nil ]; //設置動畫總時間 fishAni.animationDuration=1.0; //設置重復次數,0表示不重復 fishAni.animationRepeatCount=0; //開始動畫 [fishAni startAnimating]; }   61、用NSTimer做一個定時器,每隔1秒執行一次 pressedDone;  -(IBAction)clickBtn:(id)sender{ NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printHello) userInfo:nil repeats:YES];  [timer fire];  }   62、利用蘋果機裡的相機進行錄像: -(void) choosePhotoBySourceType: (UIImagePickerControllerCameraCaptureMode) sourceType { m_imagePickerController = [[[UIImagePickerController alloc] init] autorelease]; m_imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; m_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; m_imagePickerController.cameraDevice =UIImagePickerControllerCameraDeviceFront;  //m_imagePickerController.cameraCaptureMode =UIImagePickerControllerCameraCaptureModeVideo; NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:m_imagePickerController.sourceType]; if ([sourceTypes containsObject:(NSString *)kUTTypeMovie ]) { m_imagePickerController.mediaTypes= [NSArray arrayWithObjects: (NSString *)kUTTypeMovie,(NSString *)kUTTypeImage,nil]; } // m_imagePickerController.cameraCaptureMode = sourceType; //m_imagePickerController.mediaTypes //imagePickerController.allowsEditing = YES; [self presentModalViewController: m_imagePickerController animated:YES];  }   -(void) takePhoto { if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [self choosePhotoBySourceType:nil]; } } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; UIButton *takePhoto = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [takePhoto setTitle:@"錄像" forState:UIControlStateNormal];  [takePhoto addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];  takePhoto.frame = CGRectMake(50,100,100,30); [self.view addSubview:takePhoto]; } 63、App中調用 iPhone的home + 電源鍵截屏功能  // 前置聲明是消除警告 CGImageRef UIGetScreenImage(); CGImageRef img = UIGetScreenImage(); UIImage* scImage=[UIImage imageWithCGImage:img]; UIImageWriteToSavedPhotosAlbum(scImage, nil, nil, nil);   64、切割圖片的方法 //切割圖片 UIImage *image = [UIImage imageNamed:@"7.jpg"]; //設置需要截取的⼤大⼩小 CGRect rect = CGRectMake(20, 50, 280, 200); //轉換 CGImageRef imageRef = image.CGImage; //截取函數 CGImageRef imageRefs = CGImageCreateWithImageInRect(imageRef, rect);  //生成uIImage UIImage *newImage = [[UIImage alloc] initWithCGImage:imageRefs];  //添加到imageView中 imageView = [[UIImageView alloc] initWithImage:newImage];  imageView.frame = rect;   65、如何屏蔽父view的touch事件 -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path,NULL,0,0); CGRect rect = CGRectMake(0, 100, 320, 40); CGPathAddRect(path, NULL, rect); if(CGPathContainsPoint(path, NULL, point, NO)) { [self.superview touchesBegan:nil withEvent:nil]; } CGPathRelease(path); return self;  }   66、用戶按home鍵推送通知 UIApplication *app = [UIApplication sharedApplication];  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pressHome:) name:UIApplicationDidEnterBackgroundNotification object:app]; -(void)pressHome:(NSNotification *)notification { NSLog(@"pressHome...");  }   67、在UIImageView中旋轉圖像: float rotateAngle = M_PI; //M_PI為一角度 CGAffineTransform transform =CGAffineTransformMakeRotation(rotateA ngle); imageView.transform = transform;   68、隱藏狀態欄: 方法一, [UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];  方法二, 在應用程序的Info.plist 文件中將 UIStatusBarHidden 設置為YES;    69、構建多個可拖動視圖: @interface DragView: UIImageView{ CGPoint startLocation; NSString *whichFlower; } @property (nonatomic ,retain)NSString *whichFlower; @end @implementation DragView @synthesize whichFlower;   - (void) touchesBegan:(NSSet *)touches withEvent: (UIEvent *)event{ CGPoint pt = [[touhes anyObject ] locationInView:self]; startLocation = pt; [[self superview] bringSubviewToFront:self]; } - (void) touchesMoved:(NSSet *)touches withEvent:( UIEvent *)event{ CGPoint pt = [[touches anyObject] locatonInView:self]; CGRect frame = [self frame]; frame.origin.x += pt.x – startLocation.x; frame.origin.y += pt.y - startLocation.y; [self setFrame:frame]; } @end @interface TestController :UIViewController{ UIView *contentView; } @end @implementation TestController #define MAXFLOWERS 16 CGPoint randomPoint(){  return CGPointMake(random()%6 , random()96); } - (void)loadView{ CGRect apprect = [[UIScreen mainScreen] applicationFrame];  contentView = [[UIView alloc] initWithFrame :apprect];  contentView.backgroundColor = [UIColor blackColor];  self.view = contentView; [contentView release]; for(int i=0 ; i<MAXFLOWERS; i++){ CGRect dragRect = CGRectMake(0.0f ,0.0f, 64.0f ,64.0f);  dragRect.origin = randomPoint(); DragView *dragger = [[DragView alloc] initWithFrame:dragRect];  [dragger setUserInteractionEnabled: YES]; NSString *whichFlower = [[NSArray arrayWithObjects:@”blueFlower.png”,@”pinkFlower.png”,nil] objectAtIndex: ( random() %2)]; [dragger setImage:[UIImage imageNamed:whichFlower]];  [contentView addSubview :dragger]; [dragger release]; } } - (void)dealloc{  [contentView release]; [super dealloc];  } @end   70、iPhone中加入dylib庫 加入dylib庫時,必須在info中加入頭文件路徑。/usr/include/庫名(不要後綴)   71、iPhone iPad 中App名字如何支持多語言和顯示自定義名字 建立InfoPlist.strings,本地化此文件,然後在文件內添加: CFBundleDisplayName = "xxxxxxxxxxx"; // 這樣應⽤用程序就能顯示成設置的名字“xxxxxxxxxxx”.      72、在數字鍵盤上添加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]; }  } 73、去掉iPhone應用圖標上的弧形高光 有時候我們的應用程序不需要在圖標上加上默認的高光,可以在你的應用的 Info.plist中加入: Icon already includes gloss effects YES   74、實現修改navigation的back按鈕  self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: NSLocalizedStringFromTable (@"返回", @"System", nil) style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];   75、給圖片加上陰影 UIImageView*pageContenterImageView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"onePageApple.png"]]; //添加邊框 CALayer*layer = [pageContenterImageView layer]; layer.borderColor= [[UIColor whiteColor]CGColor]; layer.borderWidth=0.0f; //添加四個邊陰影 pageContenterImageView.layer.shadowColor= [UIColor blackColor].CGColor; pageContenterImageView.layer.shadowOffset=CGSizeMake(0,0); pageContenterImageView.layer.shadowOpacity=0.5; pageContenterImageView.layer.shadowRadius=5.0; 陰影渲染會嚴重消耗內存 ,導致程序咔叽. /*陰影效果*/ //添加邊框 CALayer*layer = [self.pageContenter layer]; layer.borderColor= [[UIColorwhiteColor]CGColor]; layer.borderWidth=0.0f; //添加四個邊陰影 self.pageContenter.layer.shadowColor= [UIColorblackColor].CGColor;//陰影顏色 self.pageContenter.layer.shadowOffset=CGSizeMake(0,0);//陰影偏移 self.pageContenter.layer.shadowOpacity=0.5;//陰影不透明度 self.pageContenter.layer.shadowRadius=5.0;//陰影半徑 ⼆二、給視圖加上陰影 UIView * content=[[UIView alloc] initWithFrame:CGRectMake(100, 250, 503, 500)]; content.backgroundColor=[UIColor orangeColor]; //content.layer.shadowOffset=10; content.layer.shadowOffset = CGSizeMake(5, 3); content.layer.shadowOpacity = 0.6; content.layer.shadowColor = [UIColor blackColor].CGColor; [self.window addSubview:content];    76、UIView有一個屬性,clipsTobounds 默認情況下是NO, 如果,我們想要view2把超出的那部份隱藏起來的話,就得改變它的父視圖也 就view1的clipsTobounds屬性值。 view1.clipsTobounds = YES; 使用objective-c 建立UUID UUID是128位的值,它可以保證唯一性。通常,它是由機器本身網卡的MAC地 址和當前系統時間來生成的。 UUID是由中劃線連接而成的字符串。例如:0A326293-BCDD-4788-8F2D- C4D8E53C108B 在聲明文件中聲明一個方法: #import <UIKit/UIKit.h> @interface UUIDViewController : UIViewController { } - (NSString *) createUUID; @end 對應的實現文件中實現該方法: - (NSString *) createUUID { CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault); NSString *uuidStr = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject); CFRelease(uuidObject); return uuidStr; }   77、iPhone iPad中橫屏顯示代碼  1、強制橫屏 [application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO]; 2、在infolist⾥裡⾯面加了Supported interface orientations這⼀一項,增加之後添加四個item就是 ipad的四個⽅方向 item0 UIInterfaceOrientationLandscapeLeft item1 UIInterfaceOrientationLandscapeRight 這表明只⽀支持橫屏顯⽰示 經常讓人混淆迷惑的問題 - 數組和其他集合類   78、當一個對象被添加到一個array, dictionary, 或者 set等這樣的集合類型中的時候,集合會retain它。 對應 的,當集合類被release的時候,它會發送對應的release消息給包含在其中的對象。 因此,如果你想建立一 個包含一堆number的數組,你可以像下面示例中的幾個方法來做 NSMutableArray *array; int i; // ... for (i = 0; i < 10; i++) { NSNumber *n = [NSNumber numberWithInt: i]; [array addObject: n]; } 在這種情況下, 我們不需要retain這些number,因為array將替我們這麼做。 NSMutableArray *array; int i; // ... for (i = 0; i < 10; i++) { NSNumber *n = [[NSNumber alloc] initWithInt: i];  [array addObject: n]; [n release]; } 在這個例子中,因為你使用了-alloc去建立了一個number,所以你必須顯式的-release它,以保證retain count的平衡。因為將number加入數組的時候,已經retain它了,所以數組中的number變量不會被release   79、UIView動畫停止調用方法遇到的問題 在實現UIView的動畫的時候,並且使⽤用UIView來重復調⽤用它結束的回調時候要 注意以下⽅方法中的finished參數 -(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { if([finishied boolValue] == YES) //一定要判斷這句話,要不在程序中當多個View刷新的時候,就可能出現動畫異常的現象 { //執行想要的動作 } }   80、判斷在UIViewController中,viewWillDisappear的時候是push還是 pop出來 - (void)viewWillDisappear:(BOOL)animated { NSArray *viewControllers = self.navigationController.viewControllers; if (viewControllers.count > 1 && [viewControllers objectAtIndex:viewControllers.count-2] == self) { // View is disappearing because a new view controller was pushed onto the stack NSLog(@"New view controller was pushed"); } else if ([viewControllers indexOfObject:self] == NSNotFound) { // View is disappearing because it was popped from the stack NSLog(@"View controller was popped"); } }   81、連接字符串小技巧 NSString *string1 = @"abc / cde"; NSString *string2 = @"abc" @"cde"; NSString *string3 = @"abc" "cde"; NSLog( @"string1 is %@" , string1 );  NSLog( @"string2 is %@" , string2 ); NSLog( @"string3 is %@" , string3 );  打印結果如下: string1 is abc cde string2 is abccde   82、隨文字大小label自適應 label=[[UILabel alloc] initWithFrame:CGRectMake(50, 23, 175, 33)]; label.backgroundColor = [UIColor purpleColor]; [label setFont:[UIFont fontWithName:@"Helvetica" size:30.0]];  [label setNumberOfLines:0]; //[myLable setBackgroundColor:[UIColor clearColor]]; [self.window addSubview:label]; NSString *text = @"this is ok"; UIFont *font = [UIFont fontWithName:@"Helvetica" size:30.0]; CGSize size = [text sizeWithFont: font constrainedToSize: CGSizeMake(175.0f, 2000.0f) lineBreakMode: UILineBreakModeWordWrap]; CGRect rect= label.frame; rect.size = size; [label setFrame: rect]; [label setText: text];   83、UILabel字體加粗 //加粗 lb.font = [UIFont fontWithName:@"Helvetica-Bold" size:20]; //加粗並且傾斜 lb.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20];   84、為IOS應用組件添加圓角的方法 具體的實現是使用QuartzCore庫,下面我具體的描述一下實現過程: • 首先創建一個項目,名字叫:ipad_webwiew • 利⽤用Interface Builder添加⼀一個UIWebView,然後和相應的代碼相關聯 • 添加QuartzCore.framework 代碼實現: 頭⽂文件: #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> @interface ipad_webwiewViewController : UIViewController { IBOutlet UIWebView *myWebView; UIView *myView; } @property (nonatomic,retain) UIWebView *myWebView; @end 代碼實現: - (void)viewDidLoad { [super viewDidLoad]; //給圖層添加背景圖⽚片: //myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage; //將圖層的邊框設置為圓腳 myWebView.layer.cornerRadius = 8; myWebView.layer.masksToBounds = YES; //給圖層添加⼀一個有⾊色邊框 myWebView.layer.borderWidth = 5; myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor]; }   85、實現UIToolBar的自動消失  -(void)showBar { ! [UIView beginAnimations:nil context:nil]; ! [UIView setAnimationDuration:0.40]; ! (_toolBar.alpha == 0.0) ? (_toolBar.alpha = 1.0) : (_toolBar.alpha = 0.0); ! [UIView commitAnimations]; } - (void)viewDidAppear:(BOOL)animated { [NSObject cancelPreviousPerformRequestsWithTarget: self]; [self performSelector: @selector(delayHideBars) withObject: nil afterDelay: 3.0]; } - (void)delayHideBars { [self showBar]; }   86、自定義UINavigationItem.rightBarButtonItem UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"remote",@"mouse",@"text",nil]]; [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"home_a.png"] atIndex:0 animated:YES]; [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"myletv_a.png"] atIndex:1 animated:YES]; segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.frame = CGRectMake(0, 0, 200, 30);  [segmentedControl setMomentary:YES]; [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; self.navigationItem.rightBarButtonItem = barButtonItem;  [segmentedControl release]; UINavigationController直接返回到根viewController  [self.navigationController popToRootViewControllerAnimated:YES]; 想要從第五層直接返回到第二層或第三層,用索引的形式 [self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 2)] animated:YES];   87、鍵盤監聽事件 #ifdef __IPHONE_5_0 float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if (version >= 5.0) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil]; } #endif [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; -(void)keyboardWillShow:(NSNotification *)notification { NSValue *value = [[notification userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"]; CGRect keyboardRect = [value CGRectValue]; NSLog(@"value %@ %f",value,keyboardRect.size.height); [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.25]; keyboardHeight = keyboardRect.size.height; self.view.frame = CGRectMake(0, -(251 - (480 - 64 - keyboardHeight)), self.view.frame.size.width, self.view.frame.size.height); [UIView commitAnimations]; }   88、 ios6.0強制橫屏的方法: 在appDelegate裡調用 if (!UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {         [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];     }  
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved