Here is a summary of some iOS development tips, can greatly facilitate our development, continuous updating.

Source: Internet
Author: User

UITableView group style top blank handling//Group list header blank handling UIView *view = [[UIView alloc] Initwithframe:cgrectmake (0, 0, 0, 0.1)]; Self.tableView.tableHeaderView = view; UITableView plain Style, remove the block head stagnation effect-(void) Scrollviewdidscroll: (Uiscrollview *) scrollview{cgfloat sectionheaderheight =    Sectionhead.height; if (scrollview.contentoffset.y=0) {scrollview.contentinset = Uiedgeinsetsmake (-scrollview.contentoffset.y, 0, 0    , 0); } else if (scrollview.contentoffset.y>=sectionheaderheight) {scrollview.contentinset = Uiedgeinsetsmake (-S    Ectionheaderheight, 0, 0, 0); }} that, in fact, still use the group style bar haha.    Get the controller that contains the view-(Uiviewcontroller *) viewcontroller{uiviewcontroller *viewcontroller = nil;  Uiresponder *next = Self.nextresponder;             while (next) {if ([Next Iskindofclass:[uiviewcontroller class]]) {Viewcontroller = (Uiviewcontroller *) next;        Break    } next = Next.nextresponder; } return Viewcontroller;} Both methods delete all records of Nsuserdefaults//method one nsstring *appdomain = [[NSBundle Mainbundle] bundleidentifier];  [[Nsuserdefaults Standarduserdefaults] removepersistentdomainforname:appdomain];    Method two-(void) resetdefaults{nsuserdefaults * defs = [Nsuserdefaults standarduserdefaults];    Nsdictionary * dict = [defs dictionaryrepresentation];    For (ID key in dict) {[Defs removeobjectforkey:key]; } [Defs synchronize];}         Print system all registered font names #pragma mark-print system all registered font names void Enumeratefonts () {for (NSString *familyname in [Uifont Familynames]) {                      NSLog (@ "%@", familyname);              Nsarray *fontnames = [Uifont fontnamesforfamilyname:familyname];       For (NSString *fontname in FontNames) {NSLog (@ "\t|-%@", fontname);    Get the color of a point in the picture-(uicolor*) Getpixelcoloratlocation: (cgpoint)-Inimage: (UIImage *) image{uicolor* color = nil; Cgimageref inimage = image.    Cgimage;     Cgcontextref cgctx = [self createargbbitmapcontextfromimage:inimage]; if (Cgctx = = NULL) {return nil;/* ERROR */    } size_t w = cgimagegetwidth (inimage);    size_t h = cgimagegetheight (inimage);     CGRect rect = {{0,0},{w,h}};    Cgcontextdrawimage (Cgctx, rect, inimage);    unsigned char* data = Cgbitmapcontextgetdata (CGCTX);        if (data = NULL) {int offset = W*round (POINT.Y) +round (point.x));        int alpha = Data[offset];        int red = data[offset+1];        int green = data[offset+2];        int blue = data[offset+3];     color = [Uicolor colorwithred: (red/255.0f) Green: (green/255.0f) Blue: (blue/255.0f) Alpha: (alpha/255.0f)];    } cgcontextrelease (CGCTX);    if (data) {free (data); } return color; String inversion the first type:-(NSString *) reversewordsinstring: (NSString *) str{nsmutablestring *newstring = [[Nsmutablestring alloc]    InitWithCapacity:str.length];              for (Nsinteger i = str.length-1; I >= 0; I-) {Unichar ch = [Str characteratindex:i];        [NewString appendformat:@ "%c", CH]; } return NewString;} Second type:-(nsstring*) reversewordsinstring: (nsstring*) str{nsmutablestring *reverstring = [nsmutablestring stringWith         Capacity:str.length]; [Str enumeratesubstringsinrange:nsmakerange (0, str.length) options:nsstringenumerationreverse | Nsstringenumerationbycomposedcharactersequences usingblock:^ (NSString *substring, NSRange substringRange,NSRange                              Enclosingrange, BOOL *stop) {[reverstring appendstring:substring];         }]; return reverstring;} Disable lock screen, by default, iOS locks the screen when the device does not have a touch action for a period of time. However, there are some applications that do not require a lock screen, such as a video player. [UIApplication sharedapplication].idletimerdisabled = YES; or [[UIApplication sharedapplication] setIdleTimerDisabled: YES]; modal launch transparent interface uiviewcontroller *VC = [[Uiviewcontroller alloc] init]; Uinavigationcontroller *na = [[Uinavigationcontroller alloc] INITWITHROOTVIEWCONTROLLER:VC]; if ([[[[Uidevice Currentdevice] systemversion] floatvalue] >= 8.0) {Na.modalpresentationstyle = Uimodalpresentationo Vercurrentcontext;} else{Self.modalpresEntationstyle=uimodalpresentationcurrentcontext;} [Self Presentviewcontroller:na animated:yes completion:nil]; Xcode debug does not show memory consumption editscheme There is an option called Enable Zoombie Objects uncheck Show hidden files//show defaults write Com.apple.finder Appleshowallfiles-bool truekillall Finder//Hide defaults write Com.apple.finder appleshowallfiles-bool falsekillall Finder string split iOS by multiple symbols jump to App Store download app score [[UIApplication sharedapplication] Openurl:[nsurl urlwithstring:@ "itms-apps:/ /itunes.apple.com/webobjects/mzstore.woa/wa/viewcontentsuserreviews?type=purple+software&id=appid "]];iOS Get Pinyin for Chinese characters + (NSString *) Transform: (NSString *) chinese{//replace nsstring with nsmutablestring nsmutablestring *pinyin = [Chi        Nese Mutablecopy];        Convert Chinese characters to pinyin (bands) Cfstringtransform ((__bridge cfmutablestringref) Pinyin, NULL, Kcfstringtransformmandarinlatin, NO);        NSLog (@ "%@", pinyin);        The phonetic transcription cfstringtransform ((__bridge cfmutablestringref) Pinyin, NULL, Kcfstringtransformstripcombiningmarks, NO) are removed; NSLog (@ "%@", pinyin); Returns the nearest result return pinyin;} Manually change the color of the iOS status bar-(void) Setstatusbarbackgroundcolor: (Uicolor *) color{UIView *statusbar = [[[UIApplication]     Sharedapplication] valueforkey:@ "Statusbarwindow"] valueforkey:@ "StatusBar"];        if ([StatusBar respondstoselector: @selector (setbackgroundcolor:)]) {statusbar.backgroundcolor = color; }} to determine whether the current Viewcontroller is a push or present display of Nsarray *viewcontrollers=self.navigationcontroller.viewcontrollers; if (Viewcontrollers.count > 1) {if ([viewcontrollers objectatindex:viewcontrollers.count-1] = = self) {/    /push Way [Self.navigationcontroller Popviewcontrolleranimated:yes]; }}else{//present Way [self dismissviewcontrolleranimated:yes completion:nil];}    Get the actual used Launchimage picture-(NSString *) getlaunchimagename{cgsize viewsize = self.window.bounds.size;      Vertical screen NSString *vieworientation = @ "Portrait";        NSString *launchimagename = nil; nsarray* imagesdict = [[[NSBundle Mainbundle] InfoDictionary] valueforkey:@ "Uilaunchimages"];        For (nsdictionary* dict in imagesdict) {cgsize imageSize = cgsizefromstring (dict[@ "uilaunchimagesize"]); if (Cgsizeequaltosize (ImageSize, viewsize) && [vieworientationisequaltostring:dict[@]                Uilaunchimageorientation "]) {launchimagename = dict[@" Uilaunchimagename "]; }} return launchimagename;} iOS gets the first response on the current screen UIWindow * Keywindow = [[UIApplication sharedapplication] Keywindow]; UIView * FirstResponder = [Keywindow performselector: @selector (FirstResponder)]; Determines whether an object follows a protocol if ([ Self.selectedcontroller Conformstoprotocol: @protocol (refreshptotocol)]) {[Self.selectedcontroller performSelector : @selector (Ontriggerrefresh)];} Determines whether the view is a child view of the specified views bool Isview = [TextView IsDescendantOfView:self.view]; Nsarray quick sum maximum minimum and average nsarray *array = [Nsarray arraywithobjects:@ "2.0", @ "2.3", @ "3.0", @ "4.0", @ "ten", nil]; CGFloat sum = [[[Array valueforkeypath:@] @sum. Floatvalue "] floatvalue]; CgFloat avg = [[array valueforkeypath:@] @avg. Floatvalue "] floatvalue]; CGFloat Max =[[array valueforkeypath:@ "@max. Floatvalue"] floatvalue]; CGFloat min =[[array valueforkeypath:@ "@min. Floatvalue"] floatvalue]; NSLog (@ "%f\n%f\n%f\n%f", sum,avg,max,min); Modify placeholder text color in Uitextfield [TextField Setvalue:[uicolor Redcolor] forkeypath:@ "_placeholderlabel.textcolor"]; about the NSDateFormatter format g: Ad era, for example, Ads A.D. yy: The following 2 bits of the year YYYY: Full year mm: month, shown as 1-12mmm: month, Display for the English month shorthand, such as janmmmm: month, displayed as the English month full name, such as Janualydd: day, 2 digits, such as 02d: Day, 1-2-bit display, such as 2EEE: abbreviated days of the week, such as Suneeee: Write the day of the week, such as Sundayaa: Last afternoon, am/ PMH: When, 24-hour, 0-23k: When, 12-hour, 0-11m: minutes, 1-2-bit mm: minutes, 2 bits s: seconds, 1-2 bit ss: seconds, 2 bits s: milliseconds gets all subclasses of a class + (Nsarray *) allsubclasses{class MYCL    The "Self class";    Nsmutablearray *mysubclasses = [Nsmutablearray array];    unsigned int numofclasses;    Class *classes = objc_copyclasslist (&numOfClasses;); for (unsigned int ci = 0; CI monitors whether the iOS device has a proxy set, requires cfnetwork.frameworknsdictionary *proxysettings = (__bridge nsdictionary *) (C Fnetworkcopysystemproxysettings ()); NSARray *proxies = (__bridge Nsarray *) (Cfnetworkcopyproxiesforurl (__bridge cfurlref _nonnull) ([NSURLURLWithString:@] Http://www.baidu.com "]), (__bridge cfdictionaryref _nonnull) (proxysettings)); NSLog (@ "\n%@", proxies); Nsdictionary *settings = proxies[0]; NSLog (@ "%@", [Settings Objectforkey: (NSString *) Kcfproxyhostnamekey]); NSLog (@ "%@", [Settings Objectforkey: (NSString *) Kcfproxyportnumberkey]); NSLog (@ "%@", [Settings Objectforkey: (NSString *) Kcfproxytypekey]); if ([[Settings Objectforkey: (NSString *) Kcfproxytypekey] isequaltostring:@ "Kcfproxytypenone"]) {NSLog (@ "no proxy");} else{NSLog (@ "Set up proxy");    Arabic numerals to Chinese format + (NSString *) Translation: (NSString *) arebic{nsstring *str = arebic;    Nsarray *arabic_numerals = @[@ "1", @ "2", @ "3", @ "4", @ "5", @ "6", @ "7", @ "8", @ "9", @ "0"];    Nsarray *chinese_numerals = @[@ "One", @ "two", @ "three", @ "four", @ "five", @ "six", @ "seven", @ "eight", @ "nine" @ "0"];    Nsarray *digits = @[@ "A", @ "ten", @ "hundred", @ "thousand", @ "Million", @ "ten", @ "hundred", @ "thousand", @ "Million", @ "ten", @ "hundred", @ "thousand", @ "Mega"]; Nsdictionary *dictionary = [Nsdictionary dictionarywiThobjects:chinese_numerals Forkeys:arabic_numerals];    Nsmutablearray *sums = [Nsmutablearray array]; for (int i = 0; iBase64 encoded with NSString object or NSData object conversion//Create nsdata Objectnsdata *nsdata = [@ "IOS Developer Tips encoded in B Ase64 "Datausingencoding:nsutf8stringencoding"; Get NSString from NSData object in base64nsstring *base64encoded = [NSData base64encodedstringwithoptions:0]; Print the BASE64 encoded Stringnslog (@ "encoded:%@", base64encoded); Let's go the other ...//NSData from the Base64 encoded strnsdata *nsdatafrombase64string = [[NSData alloc] Initwi Thbase64encodedstring:base64encoded options:0]; Decoded nsstring from the nsdatansstring *base64decoded = [[NSString alloc] initwithdata:nsdatafrombase64string Encodi Ng:nsutf8stringencoding]; NSLog (@ "Decoded:%@", base64decoded); suppress Uicollectionview's implicit animation Uicollectionview when Reloaditems, an implicit fade animation is appended by default, Sometimes it's annoying, especially if your cell is a composite cell (for example, the cell uses Uistackview).   Here are a few ways to get rid of these animations//methods one [UIView performwithoutanimation:^{ [CollectionView Reloaditemsatindexpaths:@[[nsindexpath Indexpathforitem:index insection:0]];}]; Method two [UIView animatewithduration:0 animations:^{[CollectionView performbatchupdates:^{[CollectionView reloadIt    Emsatindexpaths:@[[nsindexpath Indexpathforitem:index insection:0]]; } [Completion:nil];}]; Method three [UIView Setanimationsenabled:no]; [Self.trackpanel performbatchupdates:^{[CollectionView reloaditemsatindexpaths:@[[nsindexpath IndexPathForItem: Index insection:0]];} completion:^ (BOOL finished) {[UIView setanimationsenabled:yes];}]; Let Xcode console support LLDB type of print open terminal input three commands: Touch ~/.lldbinitecho display @import UIKit >> ~/.lldbinitecho Target Stop-hook Add-o \ "Target Stop-hook disable\" >> ~/.lldbinitcocoapods pod install/pod update slow problem pod install--verbose--no-r Epo-updatepod Update--verbose--no-repo-update If you do not add the following parameters, the default is to upgrade the Cocoapods spec warehouse, add a parameter can omit this step, and then the speed will increase a lot uiimage Occupies memory size UIImage *image = [UIImage imagenamed:@ "AA"]; Nsuinteger size = cgimagegetheight (imaGe. Cgimage) * Cgimagegetbytesperrow (image. Cgimage); GCD Timer 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);

  

Here is a summary of some iOS development tips, can greatly facilitate our development, continuous updating.

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.