iOS development common code blocks worth collecting

  • 2021-01-03 21:06:27
  • OfStack

Delete the elements of a mutable array while walking through it


NSMutableArray *copyArray = [NSMutableArray arrayWithArray:array];  
NSString *str1 = @ " zhangsan " ; 
for (AddressPerson *perName in copyArray) { 
  if ([[perName name] isEqualToString:str1]) { 
    [array removeObject:perName]; 
  } 
} 

Gets 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 ");
}

Top white space handling under Group style for UITableView


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

UITableView plain style, cancel the block 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);
  }
}

Gets the controller in which an view resides


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


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


// methods 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 on 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);
    }
  }
}

Gets the color of a point in the image


- (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 1 A: 
- (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 first 2 A: 
- (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;
}

Ban on lock screen


// The first 1 Kind of 
[UIApplication sharedApplication].idleTimerDisabled = YES;
// The first 2 Kind of 
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

Modal exit transparent interface


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

0

iOS Jump to App Store to download app Ratings


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

1

Manually change the color of the iOS status bar


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

2

Display to determine whether current ViewController is push or present


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

Gets the LaunchImage image in actual use


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

4

iOS gets the first response on the current screen


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

5

Determines whether an object adheres to a protocol


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

6

Determines whether view is a child of the specified view
BOOL isView = [textView isDescendantOfView:self.view];

NSArray quickly calculated the sum maximum minimum value and average value


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

7

Modify the text color of Placeholder in UITextField
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

Gets 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 *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 ");
}

9

Cancel the implicit animation of UICollectionView


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

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

// methods 3
[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 limit of UITextField in iOS


// in viewDidLoad Registered in <UITextFieldTextDidChangeNotification> notice 
[[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 *)obj.object;
  NSString *toBeString = textField.text;

  // Get the highlights 
  UITextRange *selectedRange = [textField markedTextRange];
  UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];

  //  If the selected word is not highlighted, the number of words entered is counted and limited 
  if (!position)
  {
    if (toBeString.length > MAX_STARWORDS_LENGTH)
    {
      NSRange 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];
      }
    }
  }
}

Dear friends, today to share here, the next more exciting!


Related articles: