GCD Timer
dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_priority_default, 0);d ispatch_source_t timer = Dispatch_source_create (Dispatch_source_type_timer, 0, 0,queue);d Ispatch_source_set_timer (timer,dispatch_walltime (NULL, 0), 1.0*nsec_per_sec, 0); Execute Dispatch_source_set_event_handler per second (timer, ^{ //Countdown end, close dispatch_source_cancel (timer); Dispatch_async (Dispatch_get_main_queue (), ^{ });}); Dispatch_resume (timer);
Draw text on a picture
-(UIImage *) Imagewithtitle: (NSString *) title fontSize: (cgfloat) fontsize{//Canvas size cgsize size=cgsizemake (self.size.wi Dth,self.size.height); Create a bitmap-based context uigraphicsbeginimagecontextwithoptions (size,no,0.0);//opaque:no scale:0.0 [Self drawatpoint:cgpoint Make (0.0,0.0)]; Text centered on the canvas nsmutableparagraphstyle* paragraphstyle = [[Nsparagraphstyle Defaultparagraphstyle] mutableCopy]; Paragraphstyle.linebreakmode = nslinebreakbycharwrapping;
paragraphstyle.alignment=nstextalignmentcenter;//Text Center//Calculate the size of the text, text centered on the canvas cgsize sizetext=[title BoundingRectWithSize:self.size Options:nsstringdrawinguseslinefragmentorigin Attribute S:@{nsfontattributename:[uifont systemfontofsize:fontsize]}context:nil].size; CGFloat width = self.size.width; CGFloat height = self.size.height; CGRect rect = CGRectMake ((width-sizetext.width)/2, (Height-sizetext.height)/2, sizetext.width, sizetext.height); Draw text [title Drawinrect:rect withattributes:@{Nsfontattributename:[uifont Systemfontofsize:fontsize], nsforegroundcolorattributename:[Uicolor Whitecolor],nsparagraphstyleattributename:paragraphstyle}]; Returns the drawing of the new graphic UIImage *newimage= uigraphicsgetimagefromcurrentimagecontext (); Uigraphicsendimagecontext (); return newimage;}
Find all the child views of a view
-(Nsmutablearray *) Allsubviewsforview: (UIView *) view{ nsmutablearray *array = [Nsmutablearray arraywithcapacity : 0]; For (UIView *subview in view.subviews) { [array addobject:subview]; if (SubView.subviews.count > 0) { [array addobjectsfromarray:[self allsubviewsforview:subview]; } } return array;}
Calculate File Size
//File Size-(Long Long) Filesizeatpath: (NSString *) path{nsfilemanager *filemanager = [Nsfilemanager Defaultmanager]; if ([FileManager Fileexistsatpath:path]) {Long Long size = [FileManager attributesofitematpath:path error:nil ].filesize; return size; } return 0;} Folder Size-(long Long) Foldersizeatpath: (NSString *) path{nsfilemanager *filemanager = [Nsfilemanager Defaultmanager]; Long long foldersize = 0; if ([FileManager Fileexistsatpath:path]) {Nsarray *childerfiles = [FileManager Subpathsatpath:path]; For (NSString *filename in childerfiles) {nsstring *fileabsolutepath = [path Stringbyappendingpathcompo Nent:filename]; if ([FileManager Fileexistsatpath:fileabsolutepath]) {Long Long size = [FileManager Attributeso Fitematpath:fileabsolutepath error:nil].filesize; Foldersize + = size; }}} return foldersize;}
UIView the set part rounded corners
CGRect rect = view.bounds; Cgsize Radio = Cgsizemake (30, 30);//fillet size Uirectcorner corner = uirectcornertopleft| uirectcornertopright;//the fillet position uibezierpath *path = [Uibezierpath bezierpathwithroundedrect:rect byRoundingCorners: Corner Cornerradii:radio]; Cashapelayer *masklayer = [[Cashapelayer alloc]init];//Create shapelayermasklayer.frame = View.bounds;masklayer.path = Path . cgpath;//set Path view.layer.mask = Masklayer;
Calculates the string character length, a Chinese character is counted two characters
Method One:-(int) Converttoint: (nsstring*) strtemp{ int strlength = 0; char* p = (char*) [strtemp cstringusingencoding:nsunicodestringencoding]; for (int i=0; i<[strtemp lengthofbytesusingencoding:nsunicodestringencoding]; i++) { if (*p) { p+ +; strlength++; } else { p++; } } return strlength;} Method two:-(Nsuinteger) unicodelengthofstring: (NSString *) text{ Nsuinteger asciilength = 0; for (Nsuinteger i = 0; i < text.length; i++) { Unichar UC = [text characteratindex:i]; Asciilength + = Isascii (UC)? 1:2; } return asciilength;}
Prevent scrolling view gestures from overwriting slide gestures
[Scrollview.pangesturerecognizer Requiregesturerecognizertofail: Self.navigationController.interactivePopGestureRecognizer];
Remove the title returned from the navigation bar
[[Uibarbuttonitem appearance]setbackbuttontitlepositionadjustment:uioffsetmake (0, -60) forBarMetrics: Uibarmetricsdefault];
Whether the string contains Chinese
+ (BOOL) Checkischinese: (NSString *) string{for (int i=0; i<string.length; i++) { Unichar ch = [string CHARACTERATINDEX:I]; if (0x4e00 <= ch && ch <= 0x9fa5) { return YES; } } return NO;}
Use of Dispatch_group
dispatch_group_t Dispatchgroup = Dispatch_group_create (); Dispatch_group_enter (dispatchgroup); Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (1 * nsec_per_sec)), Dispatch_get_main_queue (), ^{ NSLog (@ "First request completed"); Dispatch_group_leave (Dispatchgroup); }); Dispatch_group_enter (dispatchgroup); Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (nsec_per_sec)), Dispatch_get_main_queue (), ^{ NSLog (@ "second request completed"); Dispatch_group_leave (Dispatchgroup); }); Dispatch_group_notify (Dispatchgroup, Dispatch_get_main_queue (), ^ () { NSLog (@ "request Complete"); });
Uitextfield every four bits plus a space to implement the proxy
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string{ //four-bit plus a space if ([string isequaltostring:@ ""]) { //delete character if (( textfield.text.length-2)% 5 = = 0) { Textfield.text = [Textfield.text substringToIndex:textField.text.length- 1]; } return YES; } else { if (textField.text.length% 5 = = 0) { Textfield.text = [NSString stringwithformat:@ "%@", Textfield.text]; } } return YES;}
Get phone-installed apps
Class c =nsclassfromstring (@ "Lsapplicationworkspace"); id s = [(ID) C performselector:nsselectorfromstring (@ " Defaultworkspace ")]; Nsarray *array = [s performselector:nsselectorfromstring (@ "allinstalledapplications")];for (ID item in array) { NSLog (@ "%@", [Item performselector:nsselectorfromstring (@ "Applicationidentifier")]); NSLog (@ "%@", [Item performselector:nsselectorfromstring (@ "Bundleversion")]); NSLog (@ "%@", [Item performselector:nsselectorfromstring (@ "shortversionstring")]);
In-app open system settings interface
iOS8 [[uiapplication sharedapplication] Openurl:[nsurl urlwithstring:uiapplicationopensettingsurlstring]];// If the app does not add permissions, the settings screen is displayed. If the app has added permissions (such as notifications), the app's settings screen is displayed. IOS8 before//Add a URL type and call the following code in the code to jump to the corresponding entry for the Settings page [[uiapplication sharedapplication] Openurl:[nsurl urlwithstring:@ " Prefs:root=wifi "]); optional values are as follows: About-prefs:root=general&path=aboutaccessibility-prefs:root=general&path= Accessibilityairplane Mode on-prefs:root=airplane_modeauto-lock-prefs:root=general&path=autolockbrightness- Prefs:root=brightnessbluetooth-prefs:root=general&path=bluetoothdate & Time-prefs:root=general&path= Date_and_timefacetime-prefs:root=facetimegeneral-prefs:root=generalkeyboard-prefs:root=general&path= Keyboardicloud-prefs:root=castleicloud Storage & Backup-prefs:root=castle&path=storage_and_ Backupinternational-prefs:root=general&path=internationallocation Services-prefs:root=location_ Servicesmusic-prefs:root=musicmusic Equalizer-prefs:root=musiC&path=eqmusic Volume limit-prefs:root=music&path=volumelimitnetwork-prefs:root=general&path= Networknike + ipod-prefs:root=nike_plus_ipodnotes-prefs:root=notesnotification-prefs:root=notificati*****_ Idphone-prefs:root=phonephotos-prefs:root=photosprofile-prefs:root=general&path= Managedconfigurationlistreset-prefs:root=general&path=resetsafari-prefs:root=safarisiri-prefs:root=general &path=assistantsounds-prefs:root=soundssoftware Update-prefs:root=general&path=software_update_ linkstore-prefs:root=storetwitter-prefs:root=twitterusage-prefs:root=general&path=usagevpn-prefs:root= General&path=network/vpnwallpaper-prefs:root=wallpaperwi-fi-prefs:root=wifi
Animation pause and start
-(void) Pauselayer: (Calayer *) layer{ cftimeinterval pausedtime = [Layer Converttime:cacurrentmediatime () Fromlayer:nil]; Layer.speed = 0.0; Layer.timeoffset = Pausedtime;} -(void) Resumelayer: (Calayer *) layer{ cftimeinterval pausedtime = [Layer Timeoffset]; Layer.speed = 1.0; Layer.timeoffset = 0.0; Layer.begintime = 0.0; Cftimeinterval timesincepause = [Layer Converttime:cacurrentmediatime () Fromlayer:nil]-pausedtime; Layer.begintime = Timesincepause;}
Formatting numbers in the iOS version
With Nsnumberformatter, you can also set the format of the NSNumber output. For example, the following code: Nsnumberformatter *formatter = [[Nsnumberformatter alloc] Init];formatter.numberstyle = Nsnumberformatterdecimalstyle; NSString *string = [formatter stringfromnumber:[nsnumber numberwithint:123456789]; NSLog (@ "formatted number string:%@", string);//output: [1223:403] Formatted number string:123,456,789// Where the Nsnumberformatter class has an attribute NumberStyle, which is an enumerated type, setting different values can output a different number format. The enumeration includes: TypeDef ns_enum (Nsuinteger, nsnumberformatterstyle) {Nsnumberformatternostyle = Kcfnumberformatternostyle, NS Numberformatterdecimalstyle = Kcfnumberformatterdecimalstyle, Nsnumberformattercurrencystyle = Kcfnumberformattercurrencystyle, Nsnumberformatterpercentstyle = Kcfnumberformatterpercentstyle, Nsnumberformatterscientificstyle = Kcfnumberformatterscientificstyle, Nsnumberformatterspelloutstyle = kcfnumberformatterspelloutstyle};//the effect of each enumeration corresponding to the output number format is as follows: where the output of the third and last items differs depending on the locale of the system. [1243:403] formatted number string:123456789[1243:403] formatted number STRING:123,456,789[1243:403] Formatted number string:¥123,456,789.00[1243:403] formatted number string:-539,222,988%[ 1243:403] Formatted number string:1.23456789e8[1243:403] formatted number string: 123,456,789
How to get the WebView all the picture address
uiwebview-(void) Webviewdidfinishload: (UIWebView *) webview{//Here is JS, the main purpose of achieving the acquisition of the URL static NSString * const JSGETIM ages = @ "function getimages () {var objs = document.getElementsByTagName (\" img\ "); var imgscr = '; for (Var i=0;i<objs.length;i++) {imgscr = imgscr + objs[i].src + ' + '; }; return IMGSCR; };"; [WebView stringbyevaluatingjavascriptfromstring:jsgetimages];//Injection js method nsstring *urlresult = [WebView stringbyevaluatingjavascriptfromstring:@ "GetImages ()"]; Nsarray *urlarray = [Nsmutablearray arraywitharray:[urlresult componentsseparatedbystring:@ "+"]]; URLRESURLT is to get all the images of the URL splicing; Murlarray is an array of all the URLs}//wkwebview-(void) WebView: (Wkwebview *) WebView Didfinishnavigation: (null_unspecified wknavigation *) navigation{static NSString * Const JSGETIMAGES = @ "function g Etimages () {var objs = document.getElementsByTagName (\ "img\"); var imgscr = '; for (Var i=0;i<objs.length;i++) {imgscr = imgscr + objs[i].src + ' + '; }; return IMGSCR; };"; [WebView evaluatejavascript:jsgetimages Completionhandler:nil]; [WebView evaluatejavascript:@ "getimages ()" completionhandler:^ (ID _nullable result, nserror * _nullable error) {NSLog (@ "%@", result); }];}
Gets the height of the WebView
CGFloat height = [[Self.webview stringbyevaluatingjavascriptfromstring:@ "Document.body.offsetHeight"] floatvalue];
Navigation bar becomes pure transparent
First method//navigation bar Pure transparent [Self.navigationbar setbackgroundimage:[uiimage new] forbarmetrics:uibarmetricsdefault];// Remove the black line at the bottom of the navigation bar self.navigationBar.shadowImage = [UIImage new];//the second method [[Self.navigationbar subviews] objectatindex:0]. Alpha = 0;
TabBarbecomes pure transparent
[Self.tabbar setbackgroundimage:[uiimage new]];self.tabbar.shadowimage = [UIImage new];
Navigationbar according to the sliding distance gradient color realization
First-(void) Scrollviewdidscroll: (Uiscrollview *) scrollview{cgfloat offsettoshow = 200.0;//swipe to fully display CGFloat alpha = 1-(OFFSETTOSHOW-SCROLLVIEW.CONTENTOFFSET.Y)/offsettoshow; [[Self.navigationController.navigationBar subviews] objectatindex:0].alpha = alpha;} The second type-(void) Scrollviewdidscroll: (Uiscrollview *) scrollview{cgfloat offsettoshow = 200.0; CGFloat alpha = 1-(OFFSETTOSHOW-SCROLLVIEW.CONTENTOFFSET.Y)/offsettoshow; [Self.navigationController.navigationBar setshadowimage:[uiimage New]; [Self.navigationController.navigationBar setbackgroundimage:[self Imagewithcolor:[[uicolor Orangecolor] Colorwithalphacomponent:alpha]] forbarmetrics:uibarmetricsdefault];} Generate a picture of a solid color-(UIImage *) Imagewithcolor: (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;}
Common code blocks for iOS development (2)