[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]; }
七、進行網絡請求時,地址前必須加上http://字頭,否則會形成聯網失敗!! ios
#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];
十一、在對tableViewCell裏的控件進行初始化時,除了if還有else(蘋果文檔有詳細介紹) web
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:@"Switch@2x.png"] forBarMetrics:UIBarMetricsDefault]; }
1三、訪問設備數據,設備版本號,應用程序版本信息 面試
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);
1四、用瀏覽器打開連接 json
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
1五、程序進入後臺出發的方法 瀏覽器
按home鍵切換到後臺 - (void)applicationDidEnterBackground:(UIApplication *)application 按home鍵切迴應用 - (void)applicationWillEnterForeground:(UIApplication *)application
1六、若是想使subView屏蔽上層的點擊事件就使superView的userInteractionEnabled=YES,也就是隻有在父View能夠交互時纔會阻斷子view的交互。 網絡
1七、將圖片(imageView)加載到window窗口上 app
[[UIApplication sharedApplication].keyWindow addSubview:imageView];
1八、退出ios程序(不推薦主動退出程序,能夠只給用戶一個選項) iphone
- (void)applicationWillTerminate:(UIApplication *)application { exit(0); }
1九、__NSCFBoolean類型 ide
[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()
2二、修改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];
進行轉換均可以
2四、根據內容計算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,
2五、對url進行編碼和解碼
對特殊字符進行編碼 stringByAddingPercentEscapesUsingEncoding
對特殊字符進行解碼 stringByReplacingPercentEscapesUsingEncoding
2六、比較字符串
-(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; }
2八、用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