SoFunction
Updated on 2025-04-11

Common code blocks for iOS development that are worth collecting

Delete array elements while traversing variable arrays

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");
}else if ([currentLanguage containsString:@"zh-Hant"]) {
  NSLog(@"zh-Hant Traditional Chinese");
}

UITableView's Group style top blank processing

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
 = view;

In the plain style of UITableView, cancel the stagnation effect of the area header

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
  CGFloat sectionHeaderHeight = ;
  if (<=sectionHeaderHeight&&scrollView;.>=0)
  {
     = UIEdgeInsetsMake(-, 0, 0, 0);
  }
  else if(>=sectionHeaderHeight)
  {
     = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
  }
}

Get the controller where a view is located

- (UIViewController *)viewController
{
 UIViewController *viewController = nil; 
 UIResponder *next = ;
 while (next)
 {
  if ([next isKindOfClass:[UIViewController class]])
  {
   viewController = (UIViewController *)next;   
   break;  
  }  
  next = ; 
 } 
  return viewController;
}
 

Two ways to delete all records in NSUserDefaults

//Method 1NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];


//Method 2- (void)resetDefaults
{
  NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
  NSDictionary * dict = [defs dictionaryRepresentation];
  for (id key in dict)
  {
    [defs removeObjectForKey:key];
  }
  [defs synchronize];
}

 

Print all registered font names in the system

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 certain point in the picture

- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image
{

  UIColor* color = nil;
  CGImageRef inImage = ;
  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())+round());
    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:];
  for (NSInteger i =  - 1; i &gt;= 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 enumerateSubstringsInRange:NSMakeRange(0, ) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { 
     [reverString appendString:substring];             
   }];  
   return reverString;
}

No lock screen

//The first type[UIApplication sharedApplication].idleTimerDisabled = YES;
//The second type[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

Modal introduction of transparent interface

UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    = UIModalPresentationOverCurrentContext;
}
else
{
   =UIModalPresentationCurrentContext;
}

[self presentViewController:na animated:YES completion:nil];

iOS jump to App Store to download app ratings

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps:///WebObjects//wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
 

Manually change the color of iOS status bar

- (void)setStatusBarBackgroundColor:(UIColor *)color
{
  UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

  if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
  {
     = color;  
  }
}

How to determine whether the current ViewController is pushed or present

NSArray *viewcontrollers=;

if ( &gt; 1)
{
  if ([viewcontrollers objectAtIndex: - 1] == self)
  {
    //Push method    [ popViewControllerAnimated:YES];
  }
}
else
{
  //present method  [self dismissViewControllerAnimated:YES completion:nil];
}

 

Get the actual LaunchImage image

- (NSString *)getLaunchImageName
{
  CGSize viewSize = ;
  // 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) &amp;&amp; [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 whether the object has followed a certain protocol

if ([ conformsToProtocol:@protocol(RefreshPtotocol)])
{
   [ performSelector:@selector(onTriggerRefresh)];
}
 

Determine whether the view is a subview of the specified view
BOOL isView = [textView isDescendantOfView:]; 

NSArray Quickly sum Maximum Min and Average

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@"] 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"]; 

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

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",@"zero"];
  NSArray *digits = @[@"indivual",@"ten",@"Hundred",@"thousand",@"Ten thousand",@"ten",@"Hundred",@"thousand",@"100 million",@"ten",@"Hundred",@"thousand",@"mega"];
  NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];

  NSMutableArray *sums = [NSMutableArray array];
  for (int i = 0; i &lt; ; i ++) {
    NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
    NSString *a = [dictionary objectForKey:substr];
    NSString *b = digits[ -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:-1];
  NSLog(@"%@",str);
  NSLog(@"%@",chinese);
  return chinese;
}

 

Cancel the implicit animation of UICollectionView

//Method 1[UIView performWithoutAnimation:^{
  [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];

//Method 2[UIView animateWithDuration:0 animations:^{
  [collectionView performBatchUpdates:^{
    [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
  } completion:nil];
}];

//Method 3[UIView setAnimationsEnabled:NO];
[ performBatchUpdates:^{
  [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
  [UIView setAnimationsEnabled:YES];
}];

Code to determine whether 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 limit for UITextField in iOS

//Register the <UITextFieldTextDidChangeNotification> notification in viewDidLoad[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) 
     name:@"UITextFieldTextDidChangeNotification" object:myTextField];
//Implement the listening method#pragma mark - Notification Method
-(void)textFieldEditChanged:(NSNotification *)obj
{
  UITextField *textField = (UITextField *);
  NSString *toBeString = ;

  //Get the highlighted part  UITextRange *selectedRange = [textField markedTextRange];
  UITextPosition *position = [textField positionFromPosition: offset:0];

  // If there are no highlighted characters, the number of words that have been entered will be counted and restricted.  if (!position)
  {
    if ( &gt; MAX_STARWORDS_LENGTH)
    {
      NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
      if ( == 1)
      {
         = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
      }
      else
      {
        NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
         = [toBeString substringWithRange:rangeRange];
      }
    }
  }
}

Friends, that’s all for today, and the next issue will be more exciting!