1.播放视频
在单独页播放,使用以下方法
MPMoviePlayerViewController *mpView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:VideoUrl]]; mpView.moviePlayer.controlStyle = MPMovieControlStyleFullscreen; [mpView.moviePlayer play]; [self presentMoviePlayerViewControllerAnimated:mpView];
如果要在当前页播放,使用MPMoviePlayeController, 并将MPMoviePlayeController的view做为当前页的subview加入当前页面。
2.系统UI设置相关
隐藏状态栏(顶部20像素)
1 [[UIApplication sharedApplication] setStatusBarHidden:YES];
3. 页面跳转
1 //使用导航方式跳转到新的页面(页面由右侧滑如) 2 ViewController1 *viewController = [[ViewController1 alloc] init]; 3 [self.navigationController pushViewController:viewController animated:YES];
1 //由导航出的新页面中返回(向右侧滑出) 2 [self.navigationController popViewControllerAnimated:YES];
1 //使用展示方式跳转到新页面(页面由底部滑入) 2 ViewController2 *viewController = [[ViewController2 alloc] init]; 3 [self presentViewController:viewController animated:YES completion:^{}];
1 //由present的新页面中返回(向底部滑出) 2 [self dismissViewControllerAnimated:YES completion:^{ }];
4 UI控件
4.1 UIButton
//viewDidLoad, 代码创建按钮 UIButton *newViewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; newViewBtn.frame = CGRectMake(10, 200, 100, 50); [newViewBtn addTarget:self action:@selector(NavToViewClicked:) forControlEvents:UIControlEventTouchUpInside]; [newViewBtn setTitle:@"Nav to View" forState:UIControlStateNormal]; [self.view addSubview:newViewBtn]; //*******************************************************************************
1 - (void)NavToViewClicked:(UIButton*)btn{ 2 //使用导航方式跳转到新的页面(页面由右侧滑出) 3 ViewController1 *viewController = [[ViewController1 alloc] init]; 4 [self.navigationController pushViewController:viewController animated:YES]; 5 }
4.2导航栏
1 //AppDelegate - didFinishLaunchingWithOptions中,创建带导航栏的主页面 2 self.viewController = [[NavViewController alloc] init]; 3 self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
4.3 图片局部拉伸
1 // IOS 5.0之前 2 //图片将拉升左起50、上起60的像素。 3 UIImage *img = [UIImage imageNamed:@"girl.jpg"]; 4 UIImage *bg = [img stretchableImageWithLeftCapWidth:50 topCapHeight:60]; 5 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 400)]; 6 //注意UIImageView的contendMode属性必须为UIViewContentModeScaleToFill。它也是默认值 7 //imageView.contentMode = UIViewContentModeScaleToFill; 8 imageView.image = bg;
1 // >= IOS 5.0的版本可用。 2 // 以下代码和使用stretchableImageWithLeftCapWidth作用相同。也可以用于拉升多个像素的区域 3 UIEdgeInsets set = UIEdgeInsetsMake(55, 14, 50, 45); 4 //car.jpg的尺寸为60*106 5 UIImage *bg = [[UIImage imageNamed:@"car.jpg"]resizableImageWithCapInsets:set]; 6 UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 400)]; 7 imgView.image = bg; 8 [self.view addSubview:imgView];
1 //IOS6及之后版本,可以使用 resizableImageWithCapInsets 2 //以下代码用于平铺图片(纹理效果) 3 UIImage *bg = [[UIImage imageNamed:@"car.jpg"]resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeTile]; 4 UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 400)]; 5 imgView.image = bg; 6 [self.view addSubview:imgView];
4.4 关闭屏幕键盘
1 //方法一:关闭键盘 2 [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
1 //方法二:关闭键盘 2 [[self findFirstResponderBeneathView:self] resignFirstResponder]; 3 4 - (UIView*)findFirstResponderBeneathView:(UIView*)view 5 { 6 // Search recursively for first responder 7 for ( UIView *childView in view.subviews ) { 8 if ( [childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder] ) 9 return childView; 10 UIView *result = [self findFirstResponderBeneathView:childView]; 11 if ( result ) 12 return result; 13 } 14 return nil; 15 }
1 // 将页面的主view创建为UIControl(它是UIView的子类) 2 // 这样就可一处理touchdown事件了 3 // 注意这个处理可能被其他UIControl(例如UIButton)屏蔽 4 self.view = [[UIControl alloc] init]; 5 [(UIControl *)self.view addTarget:self action:@selector(pageTouchDown:) forControlEvents:UIControlEventTouchDown]; 6 7 - (void)pageTouchDown:(UIControl*)ctrl { 8 [[[UIApplication sharedApplication] keyWindow] endEditing:YES]; 9 }
//另外如果知道当前得到焦点的是哪个控件,可以直接执行 [textField1 resignFirstResponder];
4.5 控件截图
1 - (UIImage *)CaptureImage:(UIView *)subView 2 { 3 //支持retina高分的关键 4 if(UIGraphicsBeginImageContextWithOptions != NULL) 5 { 6 UIGraphicsBeginImageContextWithOptions(subView.frame.size, NO, 0.0); 7 } else { 8 UIGraphicsBeginImageContext(subView.frame.size); 9 } 10 11 //获取图像 12 [subView.layer renderInContext:UIGraphicsGetCurrentContext()]; 13 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 14 UIGraphicsEndImageContext(); 15 16 return image; 17 }
4.6 图片保存
1 //保存图像至app目录 2 - (void)SaveImageToAppDir:(UIImage *)image 3 { 4 NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/%ld.png", random()]; 5 if ([UIImagePNGRepresentation(image) writeToFile:path atomically:YES]) { 6 NSLog(@"Succeeded! %@",path); 7 } 8 else { 9 NSLog(@"Failed!"); 10 } 11 }
1 //保存图片至系统相册 2 - (void)SaveImageToAlumb:(UIImage *)image 3 { 4 //保存过程中禁止用户操作 5 [UIApplication sharedApplication].keyWindow.userInteractionEnabled = NO; 6 7 UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSaved:didFinishSavingWithError:contextInfo:), nil); 8 } 9 10 - (void)imageSaved:(UIImage *) image 11 didFinishSavingWithError: (NSError *) error 12 contextInfo: (void *) contextInfo 13 { 14 //保存完毕后用户用户操作 15 [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES; 16 if (error) 17 { 18 NSLog(@"Save Image to Alumb Failed"); 19 NSLog(@"%@", error.localizedFailureReason); 20 } 21 else 22 { 23 NSLog(@"Save Image to Alumb Sucessed"); 24 } 25 }
4.7 返回图片数据
1 UIImage *image = ... 2 //保存为jpg 3 CGFloat ratio = 0.7; 4 NSData *dataJpg = UIImageJPEGRepresentation(image, ratio); 5 6 //保存为png 7 NSData *dataPng= UIImagePNGRepresentation(image);
5. 获取资源的路径、使用NSFileHandle操作文件、文件转码、webview控件设置透明
1 NSString *path = [[NSBundle mainBundle] pathForResource:@"webViewContent" ofType:@"html"]; 2 NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path]; 3 4 NSString *htmlString = [[NSString alloc] initWithData: 5 [readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding]; 6 7 // to make html content transparent to its parent view - 8 // 1) set the webview's backgroundColor property to [UIColor clearColor] 9 // 2) use the content in the html: <body style="background-color: transparent"> 10 // 3) opaque property set to NO 11 // 12 webView.opaque = NO; 13 webView.backgroundColor = [UIColor clearColor]; 14 [self.webView loadHTMLString:htmlString baseURL:nil]; 15 [htmlString release];
6. 时间函数相关操作。注意格式化是“yyyy”输出年数,“YYYY”输出本周所在年数。例如2012年最后两天所在的周算2013,所以这两天用YYYY格式化后输出2013
1 NSDate *myDate = [NSDate date]; 2 NSTimeInterval secondsPerDay1 = 24*60*60; 3 NSDate *yesterDay = [myDate dateByAddingTimeInterval:-secondsPerDay1];
1 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 2 [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 3 NSString *result = [formatter stringFromDate:yesterDay];
1 //GMT时间转换为本地时间 2 NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc] init]; 3 [gmtFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 4 NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 5 [gmtFormatter setTimeZone:gmt]; 6 7 NSString *str = @"2013-06-20 14:20:30"; 8 //NSDate应该总是包含GMT时间(或者叫UTC时间)。 9 NSDate *date1 = [gmtFormatter dateFromString:str]; 10 11 12 NSDateFormatter *defaultFormatter = [[NSDateFormatter alloc] init]; 13 [defaultFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 14 //默认的设置中,NSDate将按当前时区转换为NSString 15 NSString *str2 = [defaultFormatter stringFromDate:date1];
7. 获取系统空闲内存、进程占用内存
1 #import <mach/mach.h> 2 // 获取当前设备可用内存(单位:MB) 3 - (double)availableMemory 4 { 5 vm_statistics_data_t vmStats; 6 mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT; 7 kern_return_t kernReturn = host_statistics(mach_host_self(), 8 HOST_VM_INFO, 9 (host_info_t)&vmStats, 10 &infoCount); 11 12 if (kernReturn != KERN_SUCCESS) { 13 return NSNotFound; 14 } 15 16 return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0; 17 } 18 19 // 获取当前任务所占用的内存(单位:MB) 20 - (double)usedMemory 21 { 22 task_basic_info_data_t taskInfo; 23 mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT; 24 kern_return_t kernReturn = task_info(mach_task_self(), 25 TASK_BASIC_INFO, 26 (task_info_t)&taskInfo, 27 &infoCount); 28 29 if (kernReturn != KERN_SUCCESS 30 ) { 31 return NSNotFound; 32 } 33 34 return taskInfo.resident_size / 1024.0 / 1024.0; 35 }
8. alert 对话框使用
1 -(IBAction)buttonChangeTime:(id)sender 2 { 3 NSString *msg = @"message content"; 4 //非ARC的代码需要手动release alert,或者设为autorelease 5 UIAlertView *alert = [[UIAlertView alloc] 6 initWithTitle:@"button Pressed" 7 message:msg 8 delegate:self 9 cancelButtonTitle:@"确认" 10 otherButtonTitles:@"我知道了", @"好的", nil]; 11 [alert show]; 12 } 13 14 #pragma mark alert delegate 15 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 16 { 17 NSLog(@"alertView button Index=%d", buttonIndex); //cancel button的index是0,其他从1累加 18 }
9.一些工程设置
9.1 在itunes中共享文件
- 打开[工程名]-Info.plist, 添加一条“Application supports iTunes file sharing” 并设为YES
- 也可以在project navigator(cmd+1)中选中工程 -> 右侧选中Targets下的项目名 -> 顶部选中info -> 添加一行:“Application supports iTunes file sharing” 并设为YES
9.2 设置项目的url,(可以用“[appurl]:”的方式启动应用程序,同时可以传递参数)
- 在project navigator(cmd+1)中选中工程 -> 右侧选中Targets下的项目名 -> 顶部选中info -> 下方的URL Types中,URL Schemes中可以添加自定义的appurl。 可以添加多个,用逗点分割
10. 文件路径及操作绘制
需要注意的是,下面这个方法取到的Documentation目录和itunes共享目录并不相同。前者是~/Library/Documentation, 后者是~/Documents
NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)
1 //包中资源路径 2 // /var/mobile/Applications/97499D0C-39B5-4BB4-B2B5-37D2475D5580/appName.app/Default.png 3 NSString *path1 = [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"]; 4 NSLog(@"path1=\n%@\n", path1);
1 //保存到根目录 2 // /var/mobile/Applications/97499D0C-39B5-4BB4-B2B5-37D2475D5580/100.png 3 NSString *path2 = [NSHomeDirectory() stringByAppendingFormat:@"/%ld.png", 100]; 4 NSLog(@"path2=\n%@\n", path2);
1 //路径展开 2 // /var/mobile/Applications/97499D0C-39B5-4BB4-B2B5-37D2475D5580/astring.txt 3 NSString *path3 = [@"~/astring.txt" stringByExpandingTildeInPath]; 4 NSLog(@"path3=\n%@\n", path3);
1 //获取特定系统目录 2 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES); 3 // /var/mobile/Applications/97499D0C-39B5-4BB4-B2B5-37D2475D5580/Library/Documentation 4 NSLog(@"dir=\n%@\n", paths[0]); 5 6 // /var/mobile/Applications/97499D0C-39B5-4BB4-B2B5-37D2475D5580/Library/Documentation/good/day 7 NSString *path4 = [paths[0] stringByAppendingPathComponent:@"good/day"]; 8 NSLog(@"path4=\n%@\n", path4); 9 10 // /var/mobile/Applications/97499D0C-39B5-4BB4-B2B5-37D2475D5580/Library/Documentation/good/day/1.txt 11 NSString *path5 = [path4 stringByAppendingPathComponent:@"1.txt"]; 12 NSLog(@"path5=\n%@\n", path5);
1 // 创建文件夹及文件 2 NSData *data = [NSData data]; 3 NSFileManager *fm = [NSFileManager defaultManager]; 4 if (![fm createDirectoryAtPath:path4 withIntermediateDirectories:YES attributes:nil error:nil]) 5 { 6 NSLog(@"create file fail"); 7 } 8 NSError *err = [[NSError alloc] init]; 9 NSString *str = [NSString stringWithFormat:@"good text: %@ 不错啊", [NSDate date]]; 10 if (![str writeToFile:path5 atomically:YES encoding:NSUTF8StringEncoding error:&err]) 11 { 12 NSLog(@"error = %@", err); 13 }
11 网络相关
11.1 获取本地ip地址
1 #include <ifaddrs.h> 2 #include <arpa/inet.h> 3 4 - (NSString *)getIPAddress 5 { 6 NSString *address = @"error"; 7 struct ifaddrs *interfaces = NULL; 8 struct ifaddrs *temp_addr = NULL; 9 int success = 0; 10 11 //retrieve the current interfaces - returns 0 on success 12 success = getifaddrs(&interfaces); 13 if (success == 0) { 14 //Loop through linked list of interfaces 15 temp_addr = interfaces; 16 while (temp_addr != NULL) { 17 if (temp_addr->ifa_addr->sa_family == AF_INET) { 18 //Check if interface is en0 which is the wifi connection on the iPhone 19 if ([[NSString stringWithUTF8String: temp_addr->ifa_name] isEqualToString:@"en0"]) { 20 //Get NSString from C String 21 address =[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)]; 22 } 23 } 24 temp_addr = temp_addr->ifa_next; 25 } 26 } 27 //Free memory 28 freeifaddrs(interfaces); 29 NSLog(@"addrees----%@",address); 30 return address; 31 }
12. 打印控件树
主线程任意地方调用 dumpViewTree
1 - (void)dumpViewTree 2 { 3 UIView * rootView = [[[UIApplication sharedApplication] keyWindow] rootViewController].view; 4 NSMutableArray * arr = [NSMutableArray array]; 5 [self _dumpView:rootView offset:0 result:arr]; 6 7 NSLog(@"\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"); 8 9 NSMutableString * strResult = [NSMutableString string]; 10 [strResult appendString:@"\n\n"]; 11 for (NSString * str in arr) 12 { 13 [strResult appendFormat:@"%@\n", str]; 14 } 15 NSLog(@"%@",strResult); 16 17 NSLog(@"\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"); 18 } 19 20 - (void)_dumpView:(UIView *)view offset:(NSUInteger)offset result:(NSMutableArray *)arrResult 21 { 22 id nextResp = [view nextResponder]; 23 NSMutableString * str = [NSMutableString string]; 24 25 for (int i=0; i<offset; i++) 26 { 27 [str appendString:@"| "]; 28 } 29 if ([nextResp isKindOfClass:[UIViewController class]]) 30 { 31 [str appendFormat:@"[%@] ", NSStringFromClass([nextResp class])]; 32 } 33 34 [str appendFormat:@"%@", view]; 35 [arrResult addObject:str]; 36 37 for (UIView * subView in [view subviews]) 38 { 39 [self _dumpView:subView offset:offset+1 result:arrResult]; 40 } 41 }