ios常用代碼

1. 隨機數

  1. srandom(time(NULL)); //隨機數種子

  2. id d = random(); // 隨機數

複製代碼

2. 視頻播放

  1.     MPMoviePlayerController *moviePlayer;
  2.     moviePlayer = [[MPMoviePlayerController alloc]
  3.                    initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"]]];
  4.     //初始化視頻播放器對象,並傳入被播放文件的地址
  5.     moviePlayer.movieControlMode = MPMovieControlModeDefault;
  6.     [moviePlayer play];
  7.     //此處有內存溢出

複製代碼

3.  啓動界面顯示


  1. iPhone軟件啓動後的第一屏圖片是非常重要的往往就是loading載入中的意思。設置它說來也簡單,但是卻無比重要

  2. 只需要在resource裏面將你希望設置的圖片更名爲Default.png,這個圖片就可以成爲iPhone載入的缺省圖片

複製代碼

4. iPhone的系統目錄

  1. *//得到Document目錄:
  2. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  3. NSString *documentsDirectory = [paths objectAtIndex:0];

  4. //得到temp臨時目錄:
  5. NSString *tempPath = NSTemporaryDirectory();

  6. //得到目錄上的文件地址:
  7. NSString *文件地址 = [目錄地址 stringByAppendingPathComponent:@"文件名.擴展名"];

複製代碼

5. 狀態欄顯示Indicator

  1. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

複製代碼

6.app Icon顯示數字

  1. - (void)applicationDidEnterBackground:(UIApplication *)application{
  2.     [[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];
  3. }

複製代碼

7.sqlite保存地址

  1.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  2.     NSString *thePath = [paths objectAtIndex:0];
  3.     NSString *filePath = [thePath stringByAppendingPathComponent:@"kilonet1.sqlite"];
  4.    
  5.     NSString *dbPath = [[[NSBundle mainBundle] resourcePath]
  6.                         stringByAppendingPathComponent:@"kilonet2.sqlite"];  

複製代碼

8.Application退出

  1. exit(0);

複製代碼

9. AlertView,ActionSheet的cancelButton點擊事件


  1. -(void) actionSheet :(UIActionSheet *) actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex {
  2.     NSLog(@"cancel actionSheet........");
  3.     //當用戶按下cancel按鈕
  4.     if( buttonIndex == [actionSheet cancelButtonIndex]) {
  5.         exit(0);
  6.     }
  7. //    //當用戶按下destructive按鈕
  8. //    if( buttonIndex == [actionSheet destructiveButtonIndex]) {
  9. //        // DoSomething here.
  10. //    }
  11. }

  12. - (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
  13.      NSLog(@"cancel alertView........");
  14.     if (buttonIndex == [alertView cancelButtonIndex]) {
  15.         exit(0);
  16.     }
  17. }

複製代碼

10.給Window設置全局的背景圖片


  1. window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"coolblack.png"]];


複製代碼

11. UITextField文本框顯示及對鍵盤的控制

  1. #pragma mark -
  2. #pragma mark UITextFieldDelegate
  3. //控制鍵盤跳轉
  4. - (BOOL)textFieldShouldReturn:(UITextField *)textField {
  5.    
  6.     if (textField == _txtAccount) {
  7.         if ([_txtAccount.text length]==0) {
  8.             return NO;
  9.         }
  10.         [_txtPassword becomeFirstResponder];
  11.     } else if (textField == _txtPassword) {
  12.         [_txtPassword resignFirstResponder];
  13.     }
  14.    
  15.     return YES;
  16. }

  17. //輸入框背景更換
  18. -(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
  19.    
  20.     [textField setBackground:[UIImage imageNamed:@"ctext_field_02.png"]];
  21.    
  22.     return YES;
  23. }

  24. -(void) textFieldDidEndEditing:(UITextField *)textField{
  25.     [textField setBackground:[UIImage imageNamed:@"ctext_field_01.png"]];
  26. }

複製代碼

12.UITextField文本框前面空白寬度設置以及後面組合按鈕設置

  1.   //給文本輸入框後面加入空白
  2.     _txtAccount.rightView = _btnDropDown;
  3.     _txtAccount.rightViewMode =  UITextFieldViewModeAlways;
  4.    
  5.     //給文本輸入框前面加入空白
  6.     CGRect frame = [_txtAccount frame];
  7.     frame.size.width = 5;
  8.     UIView *leftview = [[UIView alloc] initWithFrame:frame];
  9.     _txtAccount.leftViewMode = UITextFieldViewModeAlways;
  10.     _txtAccount.leftView = leftview;



複製代碼

13. UIScrollView 設置滑動不超出本身範圍

  1. [fcScrollView setBounces:NO];


複製代碼

14. 遍歷View裏面所有的Subview


  1.     NSLog(@"subviews count=%d",[self.view.subviews count]);
  2.     if ([self.view.subviews count] > 0) {
  3.         for (UIView *curView in self.view.subviews) {
  4.                        NSLog(@"view.subviews=%@", [NSString stringWithUTF8String:object_getClassName(curView)]);
  5.         }
  6.     }


複製代碼

15. 在drawRect裏畫文字

  1.    UIFont * f = [UIFont systemFontOfSize:20];

  2.     [[UIColor darkGrayColor] set];
  3.     NSString * text = @"hi \nKiloNet";
  4.     [text drawAtPoint:CGPointMake(center.x,center.y) withFont:f];


複製代碼

16. NSArray查找是否存在對象時用indexOfObject,如果不存在則返回爲NSNotFound.


17. NString與NSArray之間相互轉換

  1. array = [string componentsSeparatedByString:@","];
  2. string = [[array valueForKey:@"description"] componentsJoinedByString:@","];

複製代碼

18. TabController隨意切換tab bar


  1. [self.tabBarController setSelectedIndex:tabIndex];

  2. 或者 self.tabBarController.selectedIndex = tabIndex;

  3. 或者實現下面的delegate來撲捉tab bar的事件:

  4. 代碼
  5. -(BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
  6.    
  7.     if ([viewController.tabBarItem.title isEqualToString: NSLocalizedString(@"Logout",nil)]) {
  8.         [self showLogout];
  9.         return NO;
  10.     }
  11.     return YES;
  12. }

複製代碼

19. 自定義View之間切換動畫

  1. - (void) pushController: (UIViewController*) controller
  2.          withTransition: (UIViewAnimationTransition) transition
  3. {
  4.     [UIView beginAnimations:nil context:NULL];
  5.     [self pushViewController:controller animated:NO];
  6.     [UIView setAnimationDuration:.5];
  7.     [UIView setAnimationBeginsFromCurrentState:YES];        
  8.     [UIView setAnimationTransition:transition forView:self.view cache:YES];
  9.     [UIView commitAnimations];
  10. }
  11.     或者:

  12. 代碼
  13. CATransition *transition = [CATransition animation];
  14. transition.duration = kAnimationDuration;
  15. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  16. transition.type = kCATransitionPush;
  17. transition.subtype = kCATransitionFromTop;
  18. transitioning = YES;
  19. transition.delegate = self;
  20. [self.navigationController.view.layer addAnimation:transition forKey:nil];
  21.    
  22. self.navigationController.navigationBarHidden = NO;
  23. [self.navigationController pushViewController:tableViewController animated:YES];

複製代碼

20. UIWebView加載時白色顯示問題解決以及字體統一設置

  1.     <B>uiWebView</B>.opaque = NO;

複製代碼

21.計算字符串長度

  1. CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size:18]].width;

複製代碼

22.時間轉換NSString & NSDate

  1. -(NSDate *)NSStringDateToNSDate:(NSString *)string {   

  2.     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  3.     [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
  4.     [formatter setDateFormat:@"yyyy-MM-dd"];
  5.     NSDate *date = [formatter dateFromString:string];
  6.     [formatter release];
  7.     return date;
  8. }
  9. NSString *year = [myDate descriptionWithCalendarFormat:@"%Y" timeZone:nil locale:nil];

  10. or
  11. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  12. [formatter setDateFormat:@"yyyy"];

  13. //Optionally for time zone converstions
  14. [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

  15. NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

複製代碼

23.模擬器的文件位置

  1. 其中#username#表示當前用戶名:
  2. /Users/#username#/Library/Application Support/iPhone Simulator/User/Applications/



複製代碼

24.UISearchBar時背景透明

  1. [[searchbar.subviews objectAtIndex:0]removeFromSuperview];

複製代碼

25. 圖像與緩存

  1. UIImageView *wallpaper = [[UIImageView alloc] initWithImage:
  2.         [UIImage imageNamed:@"icon.png"]]; // 會緩存圖片



  3. UIImageView *wallpaper = [[UIImageView alloc] initWithImage:
  4.         [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不會緩存圖片

複製代碼

26.常用的對視圖圖層(layer)的操作

  1. 對圖層的操作:

  2. (1.給圖層添加背景圖片:
  3. myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage;

  4. (2.將圖層的邊框設置爲圓腳
  5. myWebView.layer.cornerRadius = 8;
  6. myWebView.layer.masksToBounds = YES;

  7. (3.給圖層添加一個有色邊框
  8. myWebView.layer.borderWidth = 5;
  9. myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];



複製代碼

27. UIPopoverController 使用

  1. -(void) onSetting:(id) sender {

  2.     SplitBaseController *detail = [[SettingServerController alloc] init];

  3.    
  4.     CGRect frame = [(UIView *)sender frame];
  5.     frame.origin.y = 0;
  6.    
  7.     UIPopoverController *popwin = [[UIPopoverController alloc] initWithContentViewController:detail];
  8.     [popwin setPopoverContentSize:CGSizeMake(400, 300) animated:YES];
  9.     popwin.delegate = self;
  10.     [popwin presentPopoverFromRect: frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

  11.     [detail release];
  12. }

複製代碼

28.在UINavigationBar中添加左箭頭返回按鈕


  1. 在iPhone裏面最討厭的控件之一就是 UINavigationBar了。這個控件樣式修改不方便,連添加按鈕也特別麻煩。下面的例子是如何手動添加帶箭頭的按鈕:

  2. UINavigationItem *item = [navBar.items objectAtIndex:0];
  3. UINavigationItem *back = [[UINavigationItem alloc] initWithTitle:@"Back"];
  4. NSArray *items = [[NSArray alloc] initWithObjects:back,item,nil];
  5. [navBar setItems:items];

  6. - (BOOL)navigationBar:(UINavigationBar *)navigationBar
  7. shouldPopItem:(UINavigationItem *)item{
  8. //在此處添加點擊back按鈕之後的操作代碼
  9. return NO;
  10. }

複製代碼

29.UILable自動換行

  1. CGSize titleBrandSizeForHeight = [titleBrand.text sizeWithFont:titleBrand.font];
  2. CGSize titleBrandSizeForLines = [titleBrand.text sizeWithFont:titleBrand.font constrainedToSize:CGSizeMake(infoWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
  3. titleBrand.numberOfLines = ceil(titleBrandSizeForLines.height/titleBrandSizeForHeight.height);
  4. if (titleBrand.numberOfLines <= 1) {
  5. titleBrand.frame = CGRectMake(5, titleBrand.frame.size.height , infoWidth, titleBrandSizeForHeight.height);
  6. }else {
  7. titleBrand.frame = CGRectMake(5, titleBrand.frame.size.height , infoWidth, titleBrand.numberOfLines*titleBrandSizeForHeight.height);
  8. }


複製代碼

30.UIButton 點擊事件

  1. //創建UIButton
  2.      UIButton *sampleButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
  3.     [sampleButton setFrame:CGRectMake(240,25,60,30)];
  4.     [sampleButton setTitle:@"聊天" forState:UIControlStateNormal];
  5.     [sampleButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
  6.     [sampleButton addTarget:self action:@selector(onBtnClick:) forControlEvents:UIControlEventTouchUpInside];//onBtnClick爲方法名稱

  7. -(void) onBtnClick:(id)sender
  8. {
  9.    NSLog(@"按鈕點擊事件");
  10. }


複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章