IOS開發基礎知識--片段13,ios基礎知識--片段
1:運行程式報the file couldn't be opened because you don't have permission to view it
解決辦法:項目—>targets->build settings->build options->changed the value of the "Compiler for C/C++/Objective-C" to Default Compiler.
2:百度地圖引用
1.1引用的是.framework形式開發包時,引入的命名空間則是#import <BaiduMapAPI/BMapKit.h>//引入所有的標頭檔#import <BaiduMapAPI/BMKMapView.h>//只引入所需的單個標頭檔如果是引入用的是.a形式開發包時,引入的命名空間則是#import “BMapKit.h"1.2百度地圖現在提供的兩個.framework的包,一個是真機一個是測試機,可以使用終端的命令把它合成一個;
3:自訂圖釘百度地圖
- (void)viewDidLoad { [super viewDidLoad]; //百度地圖初始化 _mapView=[[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NAVBARHEIGHT)]; _mapView.delegate=self; [self.view addSubview:_mapView]; //標出座標點 [self addPointAnnotation];}//添加標註- (void)addPointAnnotation{ for (int i=0; i<self.coordinates.count; i++) { coordinateBean *model=self.coordinates[i]; BMKPointAnnotation* pointAnnotation = [[BMKPointAnnotation alloc]init]; CLLocationCoordinate2D coor; coor.latitude = model.latitude; coor.longitude = model.longitude; pointAnnotation.coordinate = coor; //通過title來起到傳值的作用 pointAnnotation.title=[NSString stringWithFormat:@"%d",i]; [_mapView addAnnotation:pointAnnotation]; //顯示彈出窗 [_mapView selectAnnotation:pointAnnotation animated:YES]; //判斷那個是中心,沒有則0必傳參數 if (i==self.selectIndex) { BMKCoordinateRegion region; ////表示範圍的結構體 region.center.latitude = model.latitude;// 中心中 region.center.longitude = model.longitude; region.span.latitudeDelta = 0;//經度範圍(設定為0.1表示顯示範圍為0.2的緯度範圍) region.span.longitudeDelta = 0;//緯度範圍 [_mapView setRegion:region]; } }}//處理自訂彈出視圖- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{ if ([annotation isKindOfClass:[BMKPointAnnotation class]]) { BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myrenameMark"]; newAnnotationView.pinColor = BMKPinAnnotationColorPurple; newAnnotationView.animatesDrop = YES;// 設定該標註點動畫顯示 newAnnotationView.image = [UIImage imageNamed:self.mapPointImageName]; //把圖釘換成別的圖片 int selectIndex=[((BMKPointAnnotation *)annotation).title intValue]; //獲得值 coordinateBean *model=[self.coordinates objectAtIndex:[((BMKPointAnnotation *)annotation).title intValue]]; UIView *popView=[[UIView alloc]initWithFrame:CGRectMake(0, 3, 100, 20)]; UIImage *img=[UIImage imageNamed:@"mapViewBackground"]; UIEdgeInsets edge=UIEdgeInsetsMake(0, 20, 0, 10); img=[img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch]; UIImageView *myimage=[[UIImageView alloc] initWithImage:img]; myimage.frame=CGRectMake(30, 0, 100, 40); myimage.userInteractionEnabled=YES; [popView addSubview:myimage]; //自訂顯示的內容 UILabel *driverName = [[UILabel alloc]initWithFrame:CGRectMake(0, 3, 100, 15)]; driverName.backgroundColor=[UIColor clearColor]; driverName.text=model.title; driverName.font = [UIFont systemFontOfSize:12]; driverName.textColor = [UIColor blackColor]; driverName.textAlignment = NSTextAlignmentLeft; [myimage addSubview:driverName]; UILabel *carName = [[UILabel alloc]initWithFrame:CGRectMake(0, 18, 100, 15)]; carName.backgroundColor=[UIColor clearColor]; carName.text=model.comments; carName.font = [UIFont systemFontOfSize:12]; carName.textColor = [UIColor blackColor]; carName.textAlignment = NSTextAlignmentLeft; [myimage addSubview:carName]; BMKActionPaopaoView *pView = [[BMKActionPaopaoView alloc]initWithCustomView:popView]; pView.frame = CGRectMake(0, 0, 100, 40); ((BMKPinAnnotationView*)newAnnotationView).paopaoView = nil; ((BMKPinAnnotationView*)newAnnotationView).paopaoView = pView; newAnnotationView.tag=selectIndex+10; return newAnnotationView; } return nil;}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}/** * @author wujunyang, 15-05-12 13:05:05 * * @brief 跟對百度地圖的處理 * @param animated <#animated description#> */-(void)viewWillAppear:(BOOL)animated{ [_mapView viewWillAppear]; _mapView.delegate=self; _locationService.delegate=self;}/** * @author wujunyang, 15-01-06 10:01:53 * * 跟對百度地圖的處理 * * @param animated <#animated description#> */-(void)viewWillDisappear:(BOOL)animated{ [_mapView viewWillDisappear]; _mapView.delegate=nil; _locationService.delegate=nil;}其中有個自訂model:@interface coordinateBean : NSObject//緯度@property(assign,nonatomic)float latitude;//經度@property(assign,nonatomic)float longitude;//標題@property(strong,nonatomic)NSString *title;//註解@property(strong,nonatomic)NSString *comments;@end
4:自動隱藏和顯示工具列和導航條
toolbar屬性、toolbarItems與上一講的navigationBar、navigationItem類似。只不過toolbarItems沒有navigationItem的左右區分,它就自己一個人在做事,相當於沒有下屬。可以在toolbar上設定很多,比如背景顏色、背景圖片、背景樣式、大小位置(不過有些貌似設定無效),當然和navigationBar一樣,對於它的是否顯示和隱藏是由它的老爸即navigationController控制的。所以[self.navigationController setNavigationBarHidden:YES animated:YES];也會把底部的toolBarItems給隱藏起來,如果要隱藏導航又不想底部toolBarItems被隱藏掉,可以用普通的view替代toolBarItems;首先在viewDidLoad裡設定toolBarHidden = NO, 預設是YES(隱藏的)為了讓toolbar顯示,需要設定為NO(不隱藏)。- (void)viewDidLoad{ [super viewDidLoad]; self.title = @"隱藏導覽列"; // self.toolbarItems self.navigationController.toolbar.barStyle = self.toolBar.barStyle; self.navigationController.toolbarHidden = NO; [self.navigationController.toolbar setTranslucent:YES]; self.toolbarItems = [[[NSMutableArray alloc] initWithArray:self.toolBar.items] autorelease];} 在點擊中間button的時候的顯示和隱藏navigation bar和toolBar實現代碼如下:- (IBAction)toggleNavigationBar:(id)sender{ //Check the current state of the navigation bar... BOOL navBarState = [self.navigationController isNavigationBarHidden]; //Set the navigationBarHidden to the opposite of the current state. [self.navigationController setNavigationBarHidden:!navBarState animated:YES]; [self.navigationController setToolbarHidden:!navBarState animated:YES]; //Change the label on the button. if (navBarState) { [button setTitle:@"隱藏 Navigationr and toolbar" forState:UIControlStateNormal]; [button setTitle:@"隱藏 Navigation Bar toolbar" forState:UIControlStateHighlighted]; } else { [button setTitle:@"顯示 Navigation Bar toolbar" forState:UIControlStateNormal]; [button setTitle:@"顯示 Navigation Bar toolbar" forState:UIControlStateHighlighted]; }}
5:View代碼結構的一些建議
在viewDidload裡面只做addSubview的事情,然後在viewWillAppear裡面做布局的事情,最後在viewDidAppear裡面做Notification的監聽之類的事情。至於屬性的初始化,則交給getter去做。@interface CustomObject()@property (nonatomic, strong) UILabel *label;@end@implement#pragma mark - life cycle- (void)viewDidLoad{ [super viewDidLoad]; [self.view addSubview:self.label];}- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.label.frame = CGRectMake(1, 2, 3, 4);}#pragma mark - getters and setters- (UILabel *)label{ if (_label == nil) { _label = [[UILabel alloc] init]; _label.text = @"1234"; _label.font = [UIFont systemFontOfSize:12]; ... ... } return label;}@end注意:*重點,在get方法裡面不能寫self.noLabel;千萬不要用“點”文法,這樣會造成get方法死迴圈,因為“點”文法就是調用的get方法,所以要用底線屬性名稱的方法得到對象(在記憶體這其實是一個指標)。
6: iOS中的產生隨機數方法
產生0-x之間的隨機正整數int value =arc4random_uniform(x + 1);產生隨機正整數int value = arc4random() 通過arc4random() 擷取0到x-1之間的整數的代碼如下:int value = arc4random() % x; 擷取1到x之間的整數的代碼如下: int value = (arc4random() % x) + 1; 最後如果想產生一個浮點數,可以在項目中定義如下宏:#define ARC4RANDOM_MAX 0x100000000 然後就可以使用arc4random() 來擷取0到100之間浮點數了(精度是rand()的兩倍),代碼如下:double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);執行個體(從數組中隨機顯示出一個背景圖,再通過網路載入顯示出來): self.bgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)]; self.bgView.image=[UIImage imageNamed:@"AppBg"]; [self.view addSubview:self.bgView]; [self.view sendSubviewToBack:self.bgView]; NSDictionary *params=[[NSDictionary alloc] init]; [[HomeMainNetAPIManager sharedManager] getBackgroundImage:params andBlock:^(id data, NSError *error) { if (!error&&data) { BackgroundImageBean *groundImagebean =(BackgroundImageBean *)data; int dataNum=groundImagebean.data.count; if (groundImagebean.data&&dataNum>0) { int r=arc4random_uniform(dataNum); GroundImageBean *curBean=groundImagebean.data[r]; [self.bgView sd_setImageWithURL:[NSURL URLWithString:curBean.ImgUrl] placeholderImage:[UIImage imageNamed:@"AppBg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { dispatch_async(dispatch_get_main_queue(), ^{ self.bgView.image=image; }); }]; } } }];
7:沙箱路徑知識整理
模擬器的路徑從之前的~/Library/Application Support/iPhone Simulator移動到了~/Library/Developer/CoreSimulator/Devices/檔案都在個人使用者名稱檔案夾下的一個隱藏檔案夾裡,中文叫資產庫,他的目錄其實是Library。因為應用是在沙箱(sandbox)中的,在檔案讀寫權限上受到限制,只能在幾個目錄下讀寫檔案:Documents:應用中使用者資料可以放在這裡,iTunes備份和恢複的時候會包括此目錄tmp:存放臨時檔案,iTunes不會備份和恢複此目錄,此目錄下檔案可能會在應用退出後刪除Library/Caches:存放快取檔案,iTunes不會備份此目錄,此目錄下檔案不會在應用退出刪除iTunes在與iPhone同步時,備份所有的Documents和Library檔案。iPhone在重啟時,會丟棄所有的tmp檔案。查看方法:方法1、可以設定顯示隱藏檔案,然後在Finder下直接開啟。設定查看隱藏檔案的方法如下:開啟終端,輸入命名(1)顯示Mac隱藏檔案的命令:defaults write com.apple.finder AppleShowAllFiles -bool true(2)隱藏Mac隱藏檔案的命令:defaults write com.apple.finder AppleShowAllFiles -bool false(3)輸完單擊Enter鍵,退出終端,重新啟動Finder就可以了 重啟Finder:按一下滑鼠視窗左上方的蘋果標誌-->強制退出-->Finder-->現在能看到資產庫檔案夾了。 開啟資產庫後找到/Application Support/iPhone Simulator/檔案夾。這裡面就是模擬器的各個程式的沙箱目錄了。方法2、這種方法更方便,在Finder上點->前往->前往檔案夾,輸入/Users/username/Library/Application Support/iPhone Simulator/ 前往。username這裡寫使用者名稱。 自訂類返回各目錄路徑:#import <Foundation/Foundation.h>@interface ICSandboxHelper : NSObject+ (NSString *)homePath; // 程式主目錄,可見子目錄(3個):Documents、Library、tmp+ (NSString *)appPath; // 程式目錄,不能存任何東西+ (NSString *)docPath; // 文檔目錄,需要ITUNES同步備份的資料存這裡,可存放使用者資料+ (NSString *)libPrefPath; // 配置目錄,設定檔存這裡+ (NSString *)libCachePath; // 緩衝目錄,系統永遠不會刪除這裡的檔案,ITUNES會刪除+ (NSString *)tmpPath; // 臨時緩衝目錄,APP退出後,系統可能會刪除這裡的內容+ (BOOL)hasLive:(NSString *)path; //判斷目錄是否存在,不存在則建立實現代碼:#import "ICSandboxHelper.h"@implementation ICSandboxHelper+ (NSString *)homePath{ return NSHomeDirectory();}+ (NSString *)appPath{ NSArray * paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES); return [paths objectAtIndex:0];}+ (NSString *)docPath{ NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return [paths objectAtIndex:0];}+ (NSString *)libPrefPath{ NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); return [[paths objectAtIndex:0] stringByAppendingFormat:@"/Preference"];}+ (NSString *)libCachePath{ NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); return [[paths objectAtIndex:0] stringByAppendingFormat:@"/Caches"];}+ (NSString *)tmpPath{return [NSHomeDirectory() stringByAppendingFormat:@"/tmp"];}+ (BOOL)hasLive:(NSString *)path{ if ( NO == [[NSFileManager defaultManager] fileExistsAtPath:path] ) { return [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL]; } return NO;}