ios常用代码

本文转自http://bbs.taokejh.net/forum.php?mod=viewthread&tid=42

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



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;



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. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值