iOS Development Basics-Fragmentation 13

Source: Internet
Author: User

1: Run the program reported the file couldn ' t be opened because

You don ' t have permission to view it

2: Baidu Map reference

1.1 referring to the. Framework development package, the introduced namespace is #import <baidumapapi/bmapkit.h>//introduces all header files #import <baidumapapi/ bmkmapview.h>//only introduces the desired single-header file if it is introduced in. A as a development package, the namespace introduced is #import "BMapKit.h" 1.2 Baidu Map now offers two. Framework of the package, one is the real machine one is a test machine, you can use the terminal command to synthesize it one;

3: Custom pin Baidu Map

-(void) viewdidload {[Super viewdidload];    Baidu Map Initialization _mapview=[[bmkmapview Alloc] Initwithframe:cgrectmake (0, 0, Screen_width, screen_height-navbarheight)];    _mapview.delegate=self;        [Self.view Addsubview:_mapview]; Mark the coordinate point [self addpointannotation];} Add callout-(void) addpointannotation{for (int i=0; i<self.coordinates.count; i++) {Coordinatebean *MODEL=SELF.C                Oordinates[i];        bmkpointannotation* pointannotation = [[Bmkpointannotation alloc]init];        Cllocationcoordinate2d coor;        Coor.latitude = Model.latitude;        Coor.longitude = Model.longitude;                Pointannotation.coordinate = coor;        Through the title to play the role of the value of pointannotation.title=[nsstring stringwithformat:@ "%d", I];        [_mapview addannotation:pointannotation];                                Display popup [_mapview selectannotation:pointannotation Animated:yes]; Judging that that is the center, no then 0 must-pass parameter if (i==self.selectindex) {Bmkcoordinateregion region; Structure body representing the range region.center.latitude = model.latitude;//Center Region.center.longitude = Model.longitu            De                        Region.span.latitudeDelta = 0;//Longitude range (set to 0.1 for latitude range with display range 0.2) Region.span.longitudeDelta = 0;//Latitude Range        [_mapview setregion:region]; }}}//handles custom pop-up views-(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;//Set the callout point animated display newannotationview.image = [UIImage imageNamed:self.mapPoi   Ntimagename];        Change the pin to another picture int selectindex=[((bmkpointannotation *) annotation). Title Intvalue]; Get Value 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];        Custom display content 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 the can be recreated.} /** * @author Wujunyang, 15-05-12 13:05:05 * * @brief with the processing of Baidu map * @param animaTed < #animated description#> */-(void) Viewwillappear: (BOOL) animated{[_mapview viewwillappear];    _mapview.delegate=self; _locationservice.delegate=self;} /** * @author Wujunyang, 15-01-06 10:01:53 * * with the processing of Baidu map * * @param animated < #animated description#> */-(void) VI    Ewwilldisappear: (BOOL) animated{[_mapview viewwilldisappear];    _mapview.delegate=nil; _locationservice.delegate=nil;} There is a custom model: @interface coordinatebean:nsobject//latitude @property (assign,nonatomic) Float latitude;//Longitude @property (assign,nonatomic) float longitude;//title @property (strong,nonatomic) NSString *title;// Note @property (strong,nonatomic) nsstring *comments; @end

4: Auto Hide and show toolbars and navigation bar

The toolbar attribute, ToolbarItems, is similar to the previous Navigationbar, Navigationitem. Just ToolbarItems no navigationitem of the left and right to distinguish, it is a person in their own work, the equivalent of no subordinate. Can be set on toolbar, such as background color, background image, background style, size position (but some seem to be invalid), of course, and Navigationbar, for its display and concealment is by its father that Navigationcontroller control. So [Self.navigationcontroller Setnavigationbarhidden:yes animated:yes]; it hides the toolbaritems of the bottom, If you want to hide the navigation and do not want to hide the bottom toolbaritems, you can use ordinary view instead of ToolbarItems; first set toolbarhidden = NO in Viewdidload The default is yes (hidden) in order for the toolbar to display, it needs to be set to No (not hidden).    -(void) viewdidload{[Super Viewdidload];    Self.title = @ "Hide navigation bar";    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];} When you click on the middle button the display and hide navigation bar and toolbar implementation code are as follows:-(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:@ "Hides Navigationr and toolbar" forstate:uicontrolstatenormal];    [Button settitle:@ "Hide Navigation Bar Toolbar" forstate:uicontrolstatehighlighted];        } else {[button settitle:@] shows Navigation Bar toolbar "forstate:uicontrolstatenormal];    [Button settitle:@ "Show Navigation Bar Toolbar" forstate:uicontrolstatehighlighted]; }}

Some suggestions for 5:view code structure

In viewdidload inside only do addsubview thing, then in viewwillappear inside do layout of things, finally in viewdidappear inside do notification monitoring things. As for the initialization of the property, it is given to the getter to do. @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 Note: * Focus, in the Get method can not write Self.nolabel; do not use the "dot" syntax, this will cause the Get method to die loop, because the "point" syntax is called the Get method, so to use the underscore attribute name method to get the object (in memory this is actually a pointer).
@interface Masonryviewcontroller () @property (Nonatomic,strong) UIView *conview; @property (nonatomic,assign) int intstate; @end @implementation masonryviewcontroller-(void) viewdidload {    [super viewdidload];        [Self.view AddSubview:self.conView];} Lazy Loading-(UIView *) conview{    if (_conview==nil)    {        _conview=[[uiview alloc]init];        _conview.backgroundcolor=[uicolor Redcolor];    }    return _conview;} -(int) intstate{    _intstate=0;    return _intstate;} Layout constraint-(void) viewdidlayoutsubviews{    [Self.conview mas_makeconstraints:^ (Masconstraintmaker *make) {        Make.top.equalTo (self.view.mas_top). With.offset (+);        Make.left.equalTo (Self.view.mas_left). With.offset ();        Make.right.equalTo (self.view.mas_right). With.offset (0);        Make.height.equalTo (@50);    }];} -(void) didreceivememorywarning {    [Super didreceivememorywarning];}

A method of generating random numbers in 6:ios

Generates a random positive integer between 0-x int value =arc4random_uniform (x + 1); generates a random positive integer int value = Arc4random () Gets the code for an integer between 0 and X-1 by Arc4random () as follows: int Value = Arc4random ()% x; The code to get an integer between 1 and X is as follows: int value = (arc4random ()% x) + 1; Finally, if you want to generate a floating-point number, you can define the following macro in your project: #define ARC4RANDOM_MAX 0x100000000 then you can use Arc4random () to get a floating-point number between 0 and 100 (the precision is twice times that of Rand (). The code is as follows: double val = Floorf ((double) arc4random ()/arc4random_max) * 100.0f); instance (randomly displaying a background image from an array and then displaying it over the network): 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_a                    Sync (Dispatch_get_main_queue (), ^{self.bgview.image=image;                });            }]; }        }    }];

7: Sandbox path Knowledge collation

The path of the emulator was moved from the previous ~/library/application Support/iphone simulator to the ~/library/developer/coresimulator/devices/ The files are in a hidden folder under the personal User name folder, the Chinese is called the Repository, his directory is actually the library. Because the application is in the sandbox (sandbox), the file read and write permissions are restricted, can only read and write files in several directories: Documents: The user data in the app can be placed here, itunes Backup and recovery will include this directory tmp: storage temporary files, itunes does not back up and restore this directory, files in this directory may be deleted after the app exits library/caches: Store the cache file, itunes does not back up this directory, the files in this directory will not be removed in the app to delete itunes when syncing with iphone Back up all documents and library files. When the iphone restarts, all of the TMP files are discarded. View method: Method 1, you can set the display hidden files, and then open directly under the Finder. Here's how to set up viewing hidden files: Open terminal, enter name (1) command to display Mac hidden files: Defaults write Com.apple.finder Appleshowallfiles-bool true (2) command to hide Mac hidden files: Defaults write Com.apple.finder Appleshowallfiles-bool false (3) After you click Enter to exit the terminal, restart the finder. Restart Finder: Click the Apple icon in the upper-left corner of the window and force exit-->finder--> Now you can see the repository folder. Locate the/application Support/iphone simulator/folder after opening the repository. This is the sandbox directory of the simulator's various programs. Method 2, this method is more convenient, on the Finder point-to go to the folder, enter/users/username/library/application Support/iphone simulator/to go. Username Write the user name here. The custom class returns each directory path: #import <Foundation/Foundation.h> @interface icsandboxhelper:nsobject+ (nsstrinG *) HomePath;        Program Home directory, visible sub-directory (3):D ocuments, Library, tmp+ (NSString *) AppPath;        Program directory, can not save anything + (NSString *) DocPath;    The document directory, which requires itunes to synchronize the backup data stored here, can store user data + (NSString *) Libprefpath;    Config directory, config file stored here + (NSString *) Libcachepath;        Cache directory, the system will never delete files here, itunes will delete + (NSString *) Tmppath; Temporary cache directory, after the app exits, the system may delete the content here + (BOOL) haslive: (NSString *) path; Determine if the directory exists and does not exist create the implementation code: #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]) {retur n [[Nsfilemanager Defaultmanager] Createdirectoryatpath:path Withintermediatedirec                                                               Tories:yes Attributes:nil    Error:null]; } return NO;

Basics of iOS development-fragmentation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.