Favorites for IOS Development common code block _ios

Source: Internet
Author: User

To remove an array element while traversing a mutable array

Nsmutablearray *copyarray = [Nsmutablearray Arraywitharray:array];  
NSString *str1 = @ "Zhangsan"; 
For (Addressperson *pername in Copyarray) { 
  if ([[Pername name] isequaltostring:str1]) { 
    [array removeobject: Pername]; 
  } 
 

Get the current language of the system

NSString *currentlanguage = [[Nslocale preferredlanguages] objectatindex:0];
NSLog (@ "currentlanguage =%@", currentlanguage);

if ([Currentlanguage containsstring:@ "Zh-hans"]) {
  NSLog (@ "Zh-hans Simplified Chinese");
} else if ([Currentlanguage containsstring:@ "Zh-hant"]) {
  NSLog (@ "zh-hant Traditional Chinese");
}

UITableView group style top blank handling

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

UITableView of the plain style, remove the end of the zone head stagnation effect

-(void) Scrollviewdidscroll: (Uiscrollview *) ScrollView
{
  cgfloat sectionheaderheight = sectionhead.height;
  if (Scrollview.contentoffset.y<=sectionheaderheight&&scrollview;. contentoffset.y>=0)
  {
    Scrollview.contentinset = uiedgeinsetsmake (-scrollview.contentoffset.y, 0, 0, 0);
  }
  else if (scrollview.contentoffset.y>=sectionheaderheight)
  {
    Scrollview.contentinset = uiedgeinsetsmake (-sectionheaderheight, 0, 0, 0);
  }
}

Get the controller where a view is located

-(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

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 = 4* ((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

The first kind
[uiapplication sharedapplication].idletimerdisabled = YES;
The second
[[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];

iOS jump to App store download app rating

[[UIApplication sharedapplication] Openurl:[nsurl urlwithstring:@ "itms-apps://itunes.apple.com/webobjects/ Mzstore.woa/wa/viewcontentsuserreviews?type=purple+software&id=appid "]];

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

Nsarray *viewcontrollers=self.navigationcontroller.viewcontrollers;

if (Viewcontrollers.count > 1)
{
  if ([viewcontrollers objectatindex:viewcontrollers.count-1] = self)
  {
    //push mode
    [Self.navigationcontroller popviewcontrolleranimated:yes];
  }
}
else
{
  //present mode
  [self dismissviewcontrolleranimated:yes completion:nil];
}

Get the Launchimage picture you actually use

-(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 first response on current screen

UIWindow * Keywindow = [[UIApplication sharedapplication] Keywindow];
UIView * FirstResponder = [Keywindow performselector: @selector (FirstResponder)];

Determine if an object follows a protocol

if ([Self.selectedcontroller conformstoprotocol: @protocol (refreshptotocol)])
{
   [Self.selectedcontroller Performselector: @selector (Ontriggerrefresh)];
}

Determine if view is a child view of the specified views
BOOL Isview = [TextView IsDescendantOfView:self.view];

Nsarray fast 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"];

Gets all the 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!=);

    if (superclass)
    {
      [mysubclasses addobject:classes[ci]];
    }
  Free (classes);
  return mysubclasses;
}

Conversion of 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", @ "billion", @ "ten", @ "hundred", @ "thousand", @ "trillion"];

  Nsdictionary *dictionary = [nsdictionary dictionarywithobjects:chinese_numerals forkeys:arabic_numerals];
  Nsmutablearray *sums = [Nsmutablearray array];
    for (int i = 0; i < str.length i + +) {nsstring *substr = [Str Substringwithrange:nsmakerange (I, 1)];
    NSString *a = [dictionary objectforkey:substr];
    NSString *b = digits[str.length-i-1];
    NSString *sum = [a stringbyappendingstring:b]; if ([a isequaltostring:chinese_numerals[9]]) {if ([b isequaltostring:digits[4]] | |
      [b isequaltostring:digits[8]])
        {sum = b; if ([[[Sums Lastobject] isequaltostring:chinese_numerals[9]]) {[Sums removeLastobject];
      }}else {sum = chinese_numerals[9];
      } if ([[[Sums Lastobject] isequaltostring:sum]) {continue;
  } [sums addobject:sum];
  } nsstring *sumstr = [sums componentsjoinedbystring:@ "];
  NSString *chinese = [Sumstr substringtoindex:sumstr.length-1];
  NSLog (@ "%@", str);
  NSLog (@ "%@", Chinese);
return Chinese;

 }

Remove implicit animation from Uicollectionview

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];
}];

Code to determine if the mailbox format is correct

-(BOOL) Isvalidateemail: (NSString *) email

{

NSString *emailregex = @ "[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[  a-za-z]{2,4} ";

Nspredicate *emailtest = [nspredicate predicatewithformat:@ "SELF matches%@", Emailregex];

return [Emailtest Evaluatewithobject:email];

}

Word limits for Uitextfield in iOS

Register <UITextFieldTextDidChangeNotification> notify in viewdidload [[Nsnotificationcenter Defaultcenter]addobserver
: Self selector: @selector (textfilededitchanged:) name:@ "Uitextfieldtextdidchangenotification" Object:mytextfield];  Implementation Listener #pragma mark-notification method-(void) textfieldeditchanged: (nsnotification *) obj {Uitextfield *textfield =
  (Uitextfield *) Obj.object;

  NSString *tobestring = Textfield.text;
  Get the highlighted part uitextrange *selectedrange = [TextField markedtextrange];

  Uitextposition *position = [TextField positionFromPosition:selectedRange.start offset:0]; Without a highlighted word, words are counted and restricted if (!position) {if (Tobestring.length > Max_starwords_length) {Nsrang
      e Rangeindex = [tobestring rangeofcomposedcharactersequenceatindex:max_starwords_length];
      if (rangeindex.length = = 1) {textfield.text = [tobestring substringtoindex:max_starwords_length]; else {Nsrange Rangerange = [tobestring rangeofcomPosedcharactersequencesforrange:nsmakerange (0, max_starwords_length)];
      Textfield.text = [tobestring substringwithrange:rangerange];

 }
    }
  }
}

Small partners, today to share here, the next period is more exciting!

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.