iOS training: iOS Tips Summary, missed is not!

Source: Internet
Author: User

Today summed up some of the iOS tips to summarize, absolutely you want! Definitely have what you want!

Top blank handling under the group style of UITableView

Block List header blank handling

UIView *view = [[UIView alloc] Initwithframe:cgrectmake (0, 0, 0, 0.1)];

Self.tableView.tableHeaderView = view;

Get the controller that contains a 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;

}

Two ways to delete nsuserdefaults all records

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 a picture

-(uicolor*) Getpixelcoloratlocation: (cgpoint) point 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;

}

The second type:

-(nsstring*) reversewordsinstring: (nsstring*) str

{

nsmutablestring *reverstring = [nsmutablestring stringWithCapacity: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;

}

No 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 = Uimodalpresentationovercurrentcontext;

}

Else

{

Self.modalpresentationstyle=uimodalpresentationcurrentcontext;

}

[Self Presentviewcontroller:na animated:yes completion:nil];

Xcode debugging does not show memory consumption

Editscheme has an option called Enable Zoombie Objects uncheck

Show hidden files

Show

Defaults write Com.apple.finder Appleshowallfiles-bool true

Killall Finder

Hide

Defaults write Com.apple.finder Appleshowallfiles-bool false

Killall Finder

iOS jump to App store download app ratings

[[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 the nsstring with nsmutablestring

nsmutablestring *pinyin = [Chinese mutablecopy];

Convert Chinese characters to pinyin (bands label)

Cfstringtransform ((__bridge cfmutablestringref) Pinyin, NULL, Kcfstringtransformmandarinlatin, NO);

NSLog (@ "%@", pinyin);

Remove phonetic transcription of pinyin

Cfstringtransform ((__bridge cfmutablestringref) Pinyin, NULL, Kcfstringtransformstripcombiningmarks, NO);

NSLog (@ "%@", pinyin);

Return recent Results

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;

}

}

Determines whether the current viewcontroller is a push or a present way to display

Nsarray *viewcontrollers=self.navigationcontroller.viewcontrollers;

if (Viewcontrollers.count > 1)

{

if ([viewcontrollers objectatindex:viewcontrollers.count-1] = = self)

{

Push mode

[Self.navigationcontroller Popviewcontrolleranimated:yes];

}

}

Else

{

Present Way

[Self dismissviewcontrolleranimated:yes completion:nil];

}

Get the Launchimage pictures you actually used

-(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) && [vieworientation isequaltostring: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)];

Determine if an object follows an agreement

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 value

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 the text color of placeholder in Uitextfield

[TextField setvalue:[uicolor Redcolor] forkeypath:@ "_placeholderlabel.textcolor"];

About the format of NSDateFormatter

G: A.D., e.g. AD A.D.

YY: The latter 2 digits of the year

YYYY: Full year

MM: Month, display as 1-12

MMM: Month, abbreviated for the English month, such as Jan

MMMM: Month, display full name of the English month, such as Janualy

DD: day, 2 digits, such as 02

D: Day, 1-2-bit display, such as 2

EEE: Abbreviated day of the week, such as Sun

EEEE: Full written day of the week, such as Sunday

AA: Last afternoon, AM/PM

H: When, 24-hour, 0-23

K: When, 12-hour, 0-11

M: minutes, 1-2-bit

MM: Min., 2-bit

S: seconds, 1-2 bits

SS: Seconds, 2 bits

S: MS

Get all subclasses of a class

+ (Nsarray *) allsubclasses

{

Class MyClass = [self class];

Nsmutablearray *mysubclasses = [Nsmutablearray array];

unsigned int numofclasses;

Class *classes = objc_copyclasslist (&numOfClasses;);

for (unsigned int ci = 0; ci < numofclasses; ci++)

{

Class superclass = Classes[ci];

do{

Superclass = Class_getsuperclass (superclass);

} while (superclass && superclass! = MyClass);

if (superclass)

{

[Mysubclasses Addobject:classes[ci]];

}

}

Free (classes);

return mysubclasses;

}

Monitor whether iOS devices have agents set up, need cfnetwork.framework

Nsdictionary *proxysettings = (__bridge nsdictionary *) (Cfnetworkcopysystemproxysettings ());

Nsarray *proxies = (__bridge Nsarray *) (Cfnetworkcopyproxiesforurl (__bridge cfurlref _nonnull) ([NSURL URLWithString:@ "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 agent");

}

Else

{

NSLog (@ "Set up proxy");

}

Suppress Uicollectionview of implicit animations

Uicollectionview in Reloaditems, the default is to attach an implicit fade animation, sometimes annoying, especially if your cell is a composite cell (for example, the cell uses Uistackview).

Here are some ways to get rid of these animations

Method One

[UIView performwithoutanimation:^{

[CollectionView Reloaditemsatindexpaths:@[[nsindexpath Indexpathforitem:index insection:0]];

}];

Method Two

[UIView animatewithduration:0 animations:^{

[CollectionView performbatchupdates:^{

[CollectionView Reloaditemsatindexpaths:@[[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's console support lldb type of printing

Open Terminal Input Three command:

Touch ~/.lldbinit

echo Display @import UIKit >> ~/.lldbinit

echo Target Stop-hook add-o \ "target Stop-hook disable\" >> ~/.lldbinit

CocoaPods pod install/pod Update slow issue

Pod Install--verbose--no-repo-update

Pod 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 Occupy 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);

dispatch_source_t timer = dispatch_source_create (dispatch_source_type_timer, 0, 0,queue);

Dispatch_source_set_timer (Timer,dispatch_walltime (NULL, 0), 1.0*nsec_per_sec, 0); Executes per second

Dispatch_source_set_event_handler (Timer, ^{

@ "Countdown end, Close"

Dispatch_source_cancel (timer);

Dispatch_async (Dispatch_get_main_queue (), ^{

});

});

Dispatch_resume (timer);

Draw text on the picture to write a uiimage category

-(UIImage *) Imagewithtitle: (NSString *) title fontSize: (cgfloat) fontSize

{

Canvas size

Cgsize Size=cgsizemake (self.size.width,self.size.height);

Create a bitmap-based context

Uigraphicsbeginimagecontextwithoptions (size,no,0.0);//opaque:no scale:0.0

[Self Drawatpoint:cgpointmake (0.0,0.0)];

Text centered on the canvas

nsmutableparagraphstyle* Paragraphstyle = [[Nsparagraphstyle Defaultparagraphstyle] mutableCopy];

Paragraphstyle.linebreakmode = nslinebreakbycharwrapping;

paragraphstyle.alignment=nstextalignmentcenter;//Text Center

Calculates the size of the text, centered on the canvas

Cgsize Sizetext=[title boundingRectWithSize:self.size Options:nsstringdrawinguseslinefragmentorigin

Attributes:@{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 new drawing drawing

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;

}

iOS training: iOS Tips Summary, missed is not!

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.