Development experience Summary of iOS memo

Source: Internet
Author: User
Tags local time

Reprint from: Click to open the link

Summary of knowledge points often used or infrequently used in iOS development, collection and accumulation of several years (trampled pits). i. IPhone Size

Mobile phone Model Screen Size
IPhone 4 4s 320 * 480
IPhone 5 5s 320 * 568
IPhone 6 6s 375 * 667
iphone 6 Plus 6s Plus 414 * 736
Second, set the title color for navigation Bar
Uicolor *whitecolor = [Uicolor whitecolor];
Nsdictionary *dic = [nsdictionary dictionarywithobject:whitecolor forkey:nsforegroundcolorattributename];
[Self.navigationController.navigationBar Settitletextattributes:dic];
Iii. How to put a cgpoint into an array
Cgpoint  itemsprite1position = cgpointmake (MB);
Nsmutablearray * Array  = [[Nsmutablearray alloc] Initwithobjects:nsstringfromcgpoint (itemsprite1position), nil];
    The    process of taking values from an array is this:   
cgpoint point = cgpointfromstring ([array objectatindex:0]);

NSLog (@ "point are%@.", Nsstringfromcgpoint (point));

Thanks to @bigparis's suggestion, you can use the Nsvalue to save the basic data, and use this method more clearly and clearly.

Cgpoint  itemsprite1position = cgpointmake (MB);
Nsvalue *originvalue = [Nsvalue valuewithcgpoint:itemsprite1position];
Nsmutablearray * Array  = [[Nsmutablearray alloc] initwithobjects:originvalue, nil];
The    process of taking values from an array is this:
nsvalue *currentvalue = [array objectatindex:0];
Cgpoint point = [CurrentValue cgpointvalue];

NSLog (@ "point are%@.", Nsstringfromcgpoint (point));

Now Xcode7 after the OC support generics , you can use nsmutablearray<nsstring *> *array to save. Four, Uicolor get RGB values

Uicolor *color = [Uicolor colorwithred:0.0 green:0.0 blue:1.0 alpha:1.0];
Const CGFloat *components = cgcolorgetcomponents (color. Cgcolor);
NSLog (@ "Red:%f", components[0]);
NSLog (@ "Green:%f", components[1]);
NSLog (@ "Blue:%f", components[2]);
NSLog (@ "Alpha:%f", components[3]);
Modify the font color, size of TextField placeholder
Self.textField.placeholder = @ "username is in here!";
[Self.textfield setvalue:[uicolor Redcolor] forkeypath:@ "_placeholderlabel.textcolor"];
[Self.textfield Setvalue:[uifont boldsystemfontofsize:16] forkeypath:@ "_placeholderlabel.font"];
the distance between six and two points
Static __inline__ cgfloat cgpointdistancebetweentwopoints (cgpoint point1, Cgpoint point2) {cgfloat dx = point2.x-point1 . x; CGFloat dy = point2.y-point1.y; return sqrt (DX*DX + dy*dy);}
Vii. iOS Development-closing/Lifting keyboard method Summary

1. Click return button to close the keyboard

-(BOOL) Textfieldshouldreturn: (Uitextfield *) TextField 
{return
    [TextField resignfirstresponder]; 
}

2, click the background view to close the keyboard (your view must be inherited from Uicontrol)

[Self.view Endediting:yes];

3, you can add this phrase anywhere, you can use to unify the keyboard

[[[[UIApplication sharedapplication] Keywindow] endediting:yes];
Eight, in the use of imagesqa.xcassets need to pay attention to

When you drag a picture directly into the image into Imagesqa.xcassets, the name of the picture is retained.
at this time if the name of the picture is too long, then the name will be deposited into the imagesqa.xcassets, the name is too long will cause sourcetree judgment abnormalities. Nine, uipickerview judgment starts to choose to end

To start the selection , you need to inherit Uipickerview, create a subclass, and overload in the subclass class

-(uiview*) HitTest: (cgpoint) point withevent: (uievent*) event

When [Super Hittest:point Withevent:event] Return is not nil, the description is clicked in the Uipickerview.
End-selected , implement Uipickerview delegate method

-(void) Pickerview: (uipickerview*) Pickerview Didselectrow: (nsinteger) Row incomponent: (Nsinteger) component

When this method is invoked, the description selection is over. 10, iOS simulator keyboard events

When the iOS emulator chooses the Keybaord->connect hardware keyboard, the keyboard is not ejected.

When your code adds a

[[Nsnotificationcenter Defaultcenter] addobserver:self
                                             selector: @selector (keyboardwillhide)
                                                 name: Uikeyboardwillhidenotification
                                               Object:nil];

To get the keyboard event. Then the-(void) keyboardwillhide will not be invoked in this scenario.
because there is no keyboard to hide and display. 11, on the iOS7 on the use of size classes The black below the top

After using the size classes, the black on the upper and lower parts of the iOS7 simulator appears

You can resolve this by setting Images in General->app Icons and Launch images->launch images.xcassets source.

11. PNG 12, setting different size in size classes

Different size classes is set in font.

12. PNG 13, update Uilabel text in the thread

[Self.label1 performselectoronmainthread: @selector (setText:)                                      withobject:textdisplay
                                   Waituntildone:yes];

Label1 is a uilabel, you can use this method to update when you need to update text in a child thread.
the other uiview are the same. 14, the use of uiscrollviewkeyboarddismissmode implementation of the message app behavior

Like Messages app, it's a great experience to have the keyboard disappear when scrolling. However, it is difficult to integrate this behavior into your app. Fortunately, Apple has added a very useful attribute keyboarddismissmode to Uiscrollview, which can be a lot easier.

Now you just need to change a simple attribute in storyboard, or add a line of code, and your app can do the same thing as messages app.

This property uses the new Uiscrollviewkeyboarddismissmode Enum enumeration type. The possible values for this enum enum type are as follows:

typedef ns_enum (Nsinteger, Uiscrollviewkeyboarddismissmode) {
    Uiscrollviewkeyboarddismissmodenone,
    Uiscrollviewkeyboarddismissmodeondrag,      //dismisses the keyboard when a drag begins
    Uiscrollviewkeyboarddismissmodeinteractive,//The keyboard follows the dragging touch off screens, and May is pulled Upwar D again to cancel the dismiss
} ns_enum_available_ios (7_0);

Here are the properties you need to set to let the keyboard disappear while scrolling:

14. PNG 15, error "_sqlite3_bind_blob", referenced from:

Load Sqlite3.dylib into the framework 16, iOS7 statusbar text color

IOS7, the default status bar font color is black, to be modified to white need to set uiviewcontrollerbasedstatusbarappearance to No in infoplist, and then add in the code:
[Application setstatusbarstyle:uistatusbarstylelightcontent]; 17, get the current hard disk space

Nsfilemanager *FM = [Nsfilemanager Defaultmanager];
    Nsdictionary *fattributes = [FM attributesoffilesystemforpath:nshomedirectory () Error:nil];

    NSLog (@ "Capacity%lldg", [[Fattributes objectforkey:nsfilesystemsize] longlongvalue]/1000000000);
    NSLog (@ "Available%lldg", [[Fattributes objectforkey:nsfilesystemfreesize] longlongvalue]/1000000000);
18, to UIView set the transparency, does not affect other sub views

UIView sets the alpha value, but the contents of it are then transparent. There is no way out.

Set the transparency in background color

Like what:

[Self.testview setbackgroundcolor:[uicolor colorwithred:0.0 green:1.0 blue:1.0 alpha:0.5]];

With color alpha set, you can make the background color transparent, when other sub views are unaffected to add alpha to the color, or modify alpha values.

Returns a color in the same color spaces as the receiver with the specified alpha component.
-(Uicolor *) Colorwithalphacomponent: (cgfloat) Alpha;
eg.
[View.backgroundcolor colorwithalphacomponent:0.5];
19, change color to UIImage
Convert color to UIImage
-(UIImage *) Createimagewithcolor: (Uicolor *) color
{
    CGRect rect = CGRectMake (0.0f, 0.0f, 1.0f, 1.0f);
    Uigraphicsbeginimagecontext (rect.size);
    Cgcontextref context = Uigraphicsgetcurrentcontext ();
    Cgcontextsetfillcolorwithcolor (context, [color Cgcolor]);
    Cgcontextfillrect (context, rect);
    UIImage *theimage = Uigraphicsgetimagefromcurrentimagecontext ();
    Uigraphicsendimagecontext ();

    return theimage;
}
20. Nstimer Usage
Nstimer *timer = [Nstimer scheduledtimerwithtimeinterval:.02 target:self selector: @selector (tick:) Userinfo:nil Repeats:yes];

    [[Nsrunloop Currentrunloop] Addtimer:timer formode:nsrunloopcommonmodes];

Add a timer to the Nsrunloop. 21. Bundle Identifier Application Identifier

Bundle identifier is an application identifier that shows the difference between applications and other apps. 22, NSDate acquisition of the time a few years ago

eg. Get the date 40 years ago

Nscalendar *gregorian = [[Nscalendar alloc] Initwithcalendaridentifier:nsgregoriancalendar];
Nsdatecomponents *datecomponents = [[Nsdatecomponents alloc] init];
[Datecomponents setyear:-40];
Self.birthdate = [Gregorian datebyaddingcomponents:datecomponents todate:[nsdate Date] options:0];
23, The iOS load the start map when hiding StatusBar

Just need to add the status bar is initially hidden set to Yes in Info.plist.

23. jpg 24, IOS Development, engineering mixed arc and non-arc

In the Xcode project we can use ARC and non-arc blending modes.

If your project uses a non-ARC mode, add the-FOBJC-ARC tag for the ARC mode code file.

If your project is using ARC mode, add the-FNO-OBJC-ARC tag for code files that are not in arc mode.

How to add a label: Open: Your target-> build phases-> Compile Sources. Double-click the corresponding *.M file in the pop-up window to enter the above mentioned label-fobjc-arc/-FNO-OBJC-ARC Click Done Save 25, IOS7 boundingRectWithSize:options:attributes: Context: Calculating the use of text dimensions

The SizeWithFont:constrainedToSize:lineBreakMode of the NSString class was previously used: method, but the method has been iOS7 deprecated, And iOS7 a new BoudingRectWithSize:options:attributes:context method to replace it.
and specifically how to use it, especially that attribute

Nsdictionary *attribute = @{nsfontattributename: [Uifont systemfontofsize:13]};
Cgsize size = [@ "Related nsstring" Boundingrectwithsize:cgsizemake (0) Options:nsstringdrawingtruncateslastvisibleline | Nsstringdrawinguseslinefragmentorigin | Nsstringdrawingusesfontleading Attributes:attribute context:nil].size;
26, NSDate use attention

NSDate It is generally best to use UTC time in saving data and transferring data.

When it is displayed to the user, it needs to be converted to local time . 27. A uiviewcontroller present problem of property in Uiviewcontroller

If a property attribute in a Uiviewcontroller A is Uiviewcontroller B, after instantiation, add the Bvc.view to the main Uiviewcontroller A.view, if on the Viewb-( void) Presentviewcontroller: (Uiviewcontroller *) viewcontrollertopresent animated: (BOOL) flag completion: (void (^) ( void)) Completion Ns_available_ios (5_0), the operation will appear, " presenting view controllers on detached view controllers is Discouraged "the problem.

Thought BVC had been present to AVC, so once again there will be errors.

can use

[Self.view.window.rootViewController presentviewcontroller:imagepicker
                                                      animated:yes
                                                    completion:^{
                                                        NSLog (@ "finished");
                                                    

To solve. 28, UITableViewCell indentationlevel use

The UITableViewCell property Nsinteger Indentationlevel is used to set the cell to a Indentationlevel value, and the cell can be divided into levels.

There are also cgfloat indentationwidth; property to set the width of the indentation.

Total indent width: indentationlevel * indentationwidth 29, Activityviewcontroller use AirDrop share

Use AirDrop for sharing:

Nsarray *array = @[@ "Test1", @ "Test2"];

Uiactivityviewcontroller *ACTIVITYVC = [[Uiactivityviewcontroller alloc] Initwithactivityitems:array Applicationactivities:nil];

[Self PRESENTVIEWCONTROLLER:ACTIVITYVC animated:yes
                 completion:^{
                     NSLog (@ "Air");
                 }];

You can eject the interface:

29. PNG 30, get the height of the CGRect

Gets the height of the cgrect, in addition to self.createNewMessageTableView.frame.size.height this to get the point syntax.

You can also use Cgrectgetheight (self.createNewMessageTableView.frame) for direct access.

In addition to this method there are func cgrectgetwidth (rect:cgrect)-> cgfloat

And so on, simple methods.

Func Cgrectgetminx (rect:cgrect)-> cgfloat func cgrectgetmidx
(rect:cgrect)-> cgfloat
func Cgrectgetmaxx (rect:cgrect)-> cgfloat
func cgrectgetminy (rect:cgrect)->
31, Print%
NSString *printpercentstr = [nsstring stringwithformat:@ "percent%"];
32, in the project to see if the use of IDFA

Allentekimac-mini:jikatonggit lihuaxie$ grep-r Advertisingidentifier.
grep:./ios/framework/amapsearchkit.framework/resources:no such file or directory
Binary file./ios/framework/mamapkit.framework/mamapkit matches
Binary file./ios/framework/mamapkit.framework/versions/2.4.1.e00ba6a/mamapkit matches
Binary file./ios/framework/mamapkit.framework/versions/current/mamapkit matches
Binary file./ios/jikatong.xcodeproj/project.xcworkspace/xcuserdata/lihuaxie.xcuserdatad/ Userinterfacestate.xcuserstate matches
Allentekimac-mini:jikatonggit lihuaxie$

Open the terminal to the engineering directory and enter:
Grep-r Advertisingidentifier.

You can see that the IDFA are used in those files and will be displayed if you use them. 33. APP Shield Trigger Event

Disable user interaction when download finishes
[[UIApplication sharedapplication] Beginignoringinteractionevents];
34, set the status bar color

Color settings for status bar:

If there is no navigation bar, directly set//Make status bar background color

Self.view.backgroundColor = Color_app_main;

If you have navigation bar, add a view to the navigation bar to set the color. Status bar Color
```
UIView *view = [[UIView alloc] Initwithframe:cgrectmake (0, -20, ScreenWidth, 20)];
[View Setbackgroundcolor:color_app_main];

[ViewController.navigationController.navigationBar Addsubview:view];

### #三十五, nsdictionary turn NSString

Start
Nsdictionary *parametersdic = [Nsdictionary Dictionarywithobjectsandkeys:
Self.providerstr, Key_login_provider,
token, Key_token,
Response, Key_response,
NIL];

NSData Jsondata = Parametersdic = = Nil? Nil: [nsjsonserialization datawithjsonobject:parametersdic options:0 Error:nil];
NSString requestbody = [[NSString alloc] Initwithdata:jsondata encoding:nsutf8stringencoding];

Converts a dictionary to a nsdata, and data is converted to a string.

### #三十六, iOS7 UIButton setimage did not work
if setting image in IOS7 does not take effect.

then it indicates that the UIButton enable property is not in effect. * * You need to set the enable to Yes. * *

### #三十七, user-agent judge
the device UIWebView will be based on the value of User-agent to determine which interface to display.
if it needs to be set to global, it is loaded directly when the application starts.

(void) Appenduseragent
{
NSString oldagent = [self. WebView stringbyevaluatingjavascriptfromstring:@ "Navigator.useragent"];
NSString newagent = [oldagent stringbyappendingstring:@ "IOS"];

Nsdictionary *dic = [[Nsdictionary alloc] Initwithobjectsandkeys:

                   Newagent, @ "useragent", nil];

[[Nsuserdefaults Standarduserdefaults] registerdefaults:dic];
}
```
@ "IOS" for added customizations. 38, uipasteboard shielding paste option

When the Uipasteboard string is set to @ "", then string becomes nil. The Paste option will not appear. 39, Class_addmethod use

when the ARC environment

Class_addmethod ([Self class], @selector (resolvethismethoddynamically), (IMP) Mymethodimp, "v@:");

Use the time @selector need to use super class, otherwise it will be an error.
when the MRC environment

Class_addmethod ([Emptyclass class], @selector (SayHello2), (IMP) SayHello, "v@:");

can be defined arbitrarily. However, the system will be warned, ignoring the warning. 40, afnetworking transmission form-data

Converts the JSON data into NSData and puts it into the body of the request . Sending to the server is the Form-data format. 41, NOT NULL judgment attention

BOOL hasbcccode = YES;
if (nil = = Bcccodestr
    | | [Bcccodestr Iskindofclass:[nsnull class]]
    | | [Bcccodestr isequaltostring:@ "])
{
    Hasbcccode = NO;
}

If not null judgment and type judgment, need new type judgment, then do not null judgment, otherwise will crash. 42, IOS 8.4 uialertview keyboard Display problem

You can determine whether the keyboard is hidden before calling Uialertview.

@property (nonatomic, assign) BOOL Hasshowdkeyboard; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (Showkey
                                           Board) name:uikeyboardwillshownotification

Object:nil]; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (dismiss
                                           Keyboard) Name:uikeyboarddidhidenotification

Object:nil];

-(void) Showkeyboard {self.hasshowdkeyboard = YES;}

-(void) Dismisskeyboard {self.hasshowdkeyboard = NO;} while (Self.hasshowdkeyboard) {[[Nsrunloop Currentrunloop] Runmode:nsdefaultrunloopmode beforedate:[nsdate DistantF
Uture]]; } uialertview* alerview = [[Uialertview alloc] initwithtitle:@ "message:@" Cancel modification? "Delegate:self cancelbuttontitle:@" Cancel "
Otherbuttontitles: @ "OK", nil]; [AlervIew Show]; 
43, the simulator Chinese Input method setting

The default configuration of the simulator is "Little Earth" and can only be entered in English. The method of adding Chinese is as follows:

Select Settings--->general-->keyboard-->international keyboards-->add New keyboard-->chinese Simplified ( PinYin) that we generally use the Simplified Chinese Pinyin input method, configuration, and then enter text, click on the keyboard "small Earth" can be entered in Chinese.
if not, you can choose Chinese according to the "Small Earth". 44. IPhone Number Pad

Phone's keyboard type: number pad can only enter numbers, can not switch to other input

Number_pad.png phone Pad Type: Use when dialing a phone, you can enter numbers and + *

Phone_pad.png 45, UIView self-animated flip interface

-(Ibaction) Changeimages: (ID) sender
{
    Cgcontextref context = Uigraphicsgetcurrentcontext ();

    [UIView Beginanimations:nil Context:context];
    [UIView Setanimationcurve:uiviewan
Related Article

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.