[UIScreen mainScreen].bounds
-(void)loadDocument:(NSString*)documentPathStr inView:(UIWebView*)webView { NSString *path = [[NSBundle mainBundle] pathForResource:documentPathStr ofType:nil]; NSURL *url = [NSURL fileURLWithPath:path]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; }
-(void)changeCancelBtnImage:(UISearchBar *)searchBar { for (id btn in searchBar.subviews) { if ([btn isKindOfClass:[UIButton class]]) { UIButton *tempBtn=(UIButton *)btn; [tempBtn setHighlighted:YES]; [tempBtn setBackgroundImage:[UIImage imageNamed:@"btn_yh_bt.png"] forState:UIControlStateNormal]; [tempBtn setBackgroundImage:[UIImage imageNamed:@"btn_yh_bt.png"] forState:UIControlStateHighlighted]; tempBtn.showsTouchWhenHighlighted=YES; } } }
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { if ([touch.view isKindOfClass:[UIButton class]]) { return NO; } else { return YES; } }
losisticsView.hidesBottomBarWhenPushed=YES;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //some functions ...... // 取消选中状态 [tableView deselectRowAtIndexPath:indexPath animated:NO]; }
7、进行网络请求时,地址前必须加上http://字头,不然会造成联网失败!!
#import "SBJsonWriter.h" ... SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init]; NSString *jsonString = [jsonWriter stringWithObject:myDictionary]; [jsonWriter release];
[addressTableView setContentOffset:CGPointMake(0, 140+(textField.tag-5)*50) animated:YES];
11、在对tableViewCell里的控件进行初始化时,除了if还有else(苹果文档有详细介绍)
ios4以前,在.m文件中添加如下类别 @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 //ios5 later 在viewWillAppear if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) { [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"[email protected]"] forBarMetrics:UIBarMetricsDefault]; }
13、访问设备数据,设备版本号,应用程序版本信息
UIDevice *currentDevice = [UIDevice currentDevice];//获取设备信息 NSString *model = [currentDevice model];//当前设备名称 NSString *systemVersion = [currentDevice systemVersion];//当前设备版本号 NSArray *languageArray = [NSLocale preferredLanguages]; NSString *language = [languageArray objectAtIndex:0];//用户语言 NSLocale *locale = [NSLocale currentLocale]; NSString *country = [locale localeIdentifier];//用户所在地信息 应用程序的名称和版本号等信息都保存在mainBundle的一个字典中,用下面代码可以取出来。 NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary]; NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"]; NSString*appName =[infoDict objectForKey:@"CFBundleDisplayName"]; NSString *deviceSpecs = [NSString stringWithFormat:@"%@ - %@ - %@ - %@ - %@", model, systemVersion, language, country, appVersion]; NSLog(@"Device Specs --> %@",deviceSpecs);
14、用浏览器打开链接
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
15、程序进入后台出发的方法
按home键切换到后台 - (void)applicationDidEnterBackground:(UIApplication *)application 按home键切回应用 - (void)applicationWillEnterForeground:(UIApplication *)application
16、如果想使subView屏蔽上层的点击事件就使superView的userInteractionEnabled=YES,也就是只有在父View可以交互时才会阻断子view的交互。
17、将图片(imageView)加载到window窗口上
[[UIApplication sharedApplication].keyWindow addSubview:imageView];
18、退出ios程序(不推荐主动退出程序,可以只给用户一个选项)
- (void)applicationWillTerminate:(UIApplication *)application { exit(0); }
19、__NSCFBoolean类型
[NSNumber numberWithBool:YES]消息会得到Number的子类NSCFBoolean的一个实例
Drawing属性:
第一个复选:Opaque:选中它将通知iPhoneOS,视图下的任何内容都不应绘制,并且允许IPhone的绘图方法通过一些优化来加速绘图。为什么要选中Opaque复选框呢?我们举一个例子:当Alpha的值设定为1.0(不透明),Alpha值适用于将被绘制的图像部分,但是如果某个图像为完全填充图像视图,或者图像上存在一些洞,则下方的对象将可见,而与Alpha的值无关。选中Opaque复选框后,iPhone就会知道视图下方的任何内容都不需要绘制出来。
Hidden复选框:选中它后,用户不能看到此控件。 有时隐藏空间是非常有用的,比如通过开关来控制选项的隐藏和可见性。
Clip Subviews:如果你的视图有子视图,那么这些子视图并不完全包含在其父视图中,则此复选框将确定子视图的绘制方式。如果选中了Clip Subviews,只有在父视图范围内的子视图部分被绘制出来。如果未选中Clip Subviews,则全部子视图都将绘制出来,而不管它是否在父视图内部。(默认开启)
Clear Context Before Drawing:选中后,iPhone将使用透明黑色绘制空间覆盖的所有区域,然后才实际绘制空间。因为考虑到性能问题,所以使用情况很少,默认为关闭状态。
Interaction中有两个复选框:
User Interaction Enabled:指定用户能否对此对象进行操作。对于大多数空间,此复选框都是选中的。如果不选就不能出发操作方法。但标签和图像视图默认未选中,因为经常仅用于显示静态信息
Multiple Touch:用于确保此控件能否接受多点触摸事件。支持多种复杂的手势。
ios中的控件的坐标是以一个像素为基本单位的,如果坐标精确度小于一个像素(如0.5个像素)会导致控件重影,所以坐标要去正roundf()
22、修改UISerachBar放大镜图片
for(id cc in [_searchBar subviews]) { if([cc isKindOfClass:[UITextField class]]) { UITextField *textField = (UITextField *)cc; UIImage *image = [UIImage imageNamed:@"searchText.png"] ; UIImageView *view = [[UIImageView alloc] initWithImage:image]; textField.leftView = view; } }
使用 convertRect: fromView: 或者 convertRect: toView:
例如一个视图控制器的view中有一个UITableView,UITableView的某个cell中有个UITextField,想要得到UITextField在view中的位置,就要靠上面的两个方法了。
用
CGRect rect = [self.view convertRect:textField.frame fromView:textField.superview];
或者
CGRect rect = [textField.superview convertRect:textField.frame toView:self.view];
进行转换都可以
24、根据内容计算label的高度
CGSize theTextS=[theText sizeWithFont:theFont constrainedToSize:CGSizeMake(theW, CGFLOAT_MAX) lineBreakMode:UILineBreakModeCharacterWrap];sizeWithFont参数要和label上的参数类型相同否则会导致计算高度的不准确
typedef enum { UILineBreakModeWordWrap = 0, UILineBreakModeCharacterWrap, UILineBreakModeClip, UILineBreakModeHeadTruncation, UILineBreakModeTailTruncation, UILineBreakModeMiddleTruncation, } UILineBreakMode;UILineBreakModeWordWrap = 0,
25、对url进行编码和解码
对特殊字符进行编码 stringByAddingPercentEscapesUsingEncoding
对特殊字符进行解码 stringByReplacingPercentEscapesUsingEncoding
26、比较字符串
-(void)searchName:(NSString *)theSearchName inNameArray:(NSArray *)theStoreNameArray { for (NSString *theNameStr in theStoreNameArray) { NSComparisonResult theResult=[theNameStr compare:theSearchName options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, theSearchName.length)]; if (theResult==NSOrderedSame) { [self.theReslutArray addObject:theNameStr]; } } } range的参数截取是theNameStr的长度即截取的是比较的对象 enum{ NSCaseInsensitiveSearch = 1,//不区分大小写比较 NSLiteralSearch = 2,//区分大小写比较 NSBackwardsSearch = 4,//从字符串末尾开始搜索 NSAnchoredSearch = 8,//搜索限制范围的字符串 NSNumbericSearch = 64//按照字符串里的数字为依据,算出顺序。例如 Foo2.txt < Foo7.txt < Foo25.txt //以下定义高于 mac os 10.5 或者高于 iphone 2.0 可用 , NSDiacriticInsensitiveSearch = 128,//忽略 "-" 符号的比较 NSWidthInsensitiveSearch = 256,//忽略字符串的长度,比较出结果 NSForcedOrderingSearch = 512//忽略不区分大小写比较的选项,并强制返回 NSOrderedAscending 或者 NSOrderedDescending //以下定义高于 iphone 3.2 可用 , NSRegularExpressionSearch = 1024//只能应用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比较方法,如果设置此项,可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch }
-(NSString *)calculateTimeDifFromDate:(NSDate *)theFromDate toDate:(NSDate *)theToDate { NSCalendar *cal = [NSCalendar currentCalendar]; unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; NSDateComponents *d = [cal components:unitFlags fromDate:theFromDate toDate:theToDate options:0]; int sec = [d hour]*3600+[d minute]*60+[d second]; NSLog(@"sec-----%d",sec); NSLog(@"second = %d",[d hour]*3600+[d minute]*60+[d second]); int theYear=[d year]; int theMonth=[d month]; int theDay=[d day]; int theHours=[d hour]; int theMinute=[d minute]; NSString *theDifTimeStr=[NSString stringWithFormat:@"%d年%d月%d天%d小时%d分钟",theYear,theMonth,theDay,theHours,theMinute]; return theDifTimeStr; }
28、用IB设置tableview的背景色为透明色时,当tableview为group模式时会出现黑色边角,这时需要在代码中在手动设置下tableview的background为clearcolor
在project中设置转屏选项会导致在程序启动时与真机屏幕方向不一致使程序无法运行。在ios6上要使用
supportedInterfaceOrientationsForWindow方法代替project中直接设置,就不会出现问题。
#import "ViewController.h" //保存到文件夹按钮的标签,选取图片前,这个按钮是隐藏的 #define SAVE_BUTTON_TAG 101 @interface ViewController () @end @implementation ViewController @synthesize imageView = _imageView; @synthesize saveToFileButton = _saveToFileButton; - (void)viewDidLoad { [super viewDidLoad]; //根据设置的tag获取按钮控件 self.saveToFileButton = (UIButton *)[self.view viewWithTag:SAVE_BUTTON_TAG]; //添加对象事件 [self.saveToFileButton addTarget:self action:@selector(saveToFileBtnTapped:) forControlEvents:UIControlEventTouchUpInside]; //设置为不可见 self.saveToFileButton.hidden = YES; } - (void)viewDidUnload { [self setImageView:nil]; [self setSaveToFileButton:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } - (void)dealloc { [self.imageView release]; [self.saveToFileButton release]; [super dealloc]; } - (IBAction)openAlbum:(id)sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil]; [actionSheet showInView:self.view]; [actionSheet release]; } //从文件夹读取图片 - (IBAction)readImage:(id)sender { NSString *imagePath = [self imageSavedPath:@"image.png"]; NSFileManager *fileManager = [NSFileManager defaultManager]; //判断文件是否存在 if (![fileManager fileExistsAtPath:imagePath]) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Note" message:@"文件不存在" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertView show]; [alertView release]; }else { //从指定目录读取图片 UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; self.imageView.image = image; } } //保存到文件按钮事件 - (void)saveToFileBtnTapped:(id)sender { NSString *imagePath = [self imageSavedPath:@"image.png"]; BOOL isSaveSuccess = [self saveToDocument:self.imageView.image withFilePath:imagePath]; if (isSaveSuccess) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"操作结果" message:@"保存图片成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertView show]; [alertView release]; }else { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"操作结果" message:@"保存图片失败" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertView show]; [alertView release]; } } //将选取的图片保存到目录文件夹下 -(BOOL)saveToDocument:(UIImage *) image withFilePath:(NSString *) filePath { if ((image == nil) || (filePath == nil) || [filePath isEqualToString:@""]) { return NO; } @try { NSData *imageData = nil; //获取文件扩展名 NSString *extention = [filePath pathExtension]; if ([extention isEqualToString:@"png"]) { //返回PNG格式的图片数据 imageData = UIImagePNGRepresentation(image); }else{ //返回JPG格式的图片数据,第二个参数为压缩质量:0:best 1:lost imageData = UIImageJPEGRepresentation(image, 0); } if (imageData == nil || [imageData length] <= 0) { return NO; } //将图片写入指定路径 [imageData writeToFile:filePath atomically:YES]; return YES; } @catch (NSException *exception) { NSLog(@"保存图片失败"); } return NO; } //根据图片名将图片保存到ImageFile文件夹中 -(NSString *)imageSavedPath:(NSString *) imageName { //获取Documents文件夹目录 NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentPath = [path objectAtIndex:0]; //获取文件管理器 NSFileManager *fileManager = [NSFileManager defaultManager]; //指定新建文件夹路径 NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"]; //创建ImageFile文件夹 [fileManager createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil]; //返回保存图片的路径(图片保存在ImageFile文件夹下) NSString * imagePath = [imageDocPath stringByAppendingPathComponent:imageName]; return imagePath; } #pragma Delegate method UIImagePickerControllerDelegate //图像选取器的委托方法,选完图片后回调该方法 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { if (image != nil) { //选定照片后在界面显示照片并把保存按钮设为可见 self.imageView.image = image; self.saveToFileButton.hidden = NO; } //关闭图像选择器 [self dismissModalViewControllerAnimated:YES]; } -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { //获取图片选取器 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; //指定代理 imagePicker.delegate = self; //打开图片后允许编辑 imagePicker.allowsEditing = YES; //判断图片源的类型 if (buttonIndex == 0) { if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { //相机 imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; } }else if (buttonIndex == 1) { if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){ //图片库 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; } // if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) { // //相册 // imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; // } }else if (buttonIndex == [actionSheet cancelButtonIndex]) { return; } //打开图片选择模态视图 [self presentModalViewController:imagePicker animated:YES]; [imagePicker release]; } @end