你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 值得珍藏的iOS開辟經常使用代碼塊

值得珍藏的iOS開辟經常使用代碼塊

編輯:IOS開發綜合

遍歷可變數組的同時刪除數組元素

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

獲得體系以後說話

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繁體中文");
}

UITableView的Group款式下頂部空白處置

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

UITableView的plain款式下,撤消區頭停止後果

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

獲得某個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;
}
 

兩種辦法刪除NSUserDefaults一切記載

//辦法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];


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

 

打印體系一切已注冊的字體稱號

void enumerateFonts()
{
  for(NSString *familyName in [UIFont familyNames])
  {
    NSLog(@"%@",familyName);        
    NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];    
    for(NSString *fontName in fontNames)
    {
      NSLog(@"\t|- %@",fontName);
    }
  }
}

獲得圖片某一點的色彩

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

字符串反轉

//第一種:
- (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;
}

//第二種:
- (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;
}

制止鎖屏

//第一種
[UIApplication sharedApplication].idleTimerDisabled = YES;
//第二種
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

 模態推出通明界面

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跳轉到App Store下載運用評分

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

手動更改IOS狀況欄的色彩

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

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

斷定以後ViewController是push照樣present的方法顯示

NSArray *viewcontrollers=self.navigationController.viewControllers;

if (viewcontrollers.count > 1)
{
  if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
  {
    //push方法
    [self.navigationController popViewControllerAnimated:YES];
  }
}
else
{
  //present方法
  [self dismissViewControllerAnimated:YES completion:nil];
}

 

獲得現實應用的LaunchImage圖片

- (NSString *)getLaunchImageName
{
  CGSize viewSize = self.Window.bounds.size;
  // 豎屏  
  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在以後屏幕獲得第一呼應

UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
 

斷定對象能否遵守了某協定

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

斷定view是否是指定視圖的子視圖
BOOL isView = [textView isDescendantOfView:self.view]; 

NSArray 疾速求總和 最年夜值 最小值 和 均勻值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", 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);
 

修正UITextField中Placeholder的文字色彩
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; 

獲得一個類的一切子類

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

阿拉伯數字轉中文格局

+(NSString *)translation:(NSString *)arebic
{ 
  NSString *str = arebic;
  NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
  NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
  NSArray *digits = @[@"個",@"十",@"百",@"千",@"萬",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆"];
  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;
}

 

撤消UICollectionView的隱式動畫

//辦法一
[UIView performWithoutAnimation:^{
  [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];

//辦法二
[UIView animateWithDuration:0 animations:^{
  [collectionView performDosBat target=_blank class=infotextkey>BatchUpdates:^{
    [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
  } completion:nil];
}];

//辦法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performDosBat target=_blank class=infotextkey>BatchUpdates:^{
  [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
  [UIView setAnimationsEnabled:YES];
}];

斷定郵箱格局能否准確的代碼

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

  }

iOS中UITextField的字數限制

//在viewDidLoad中注冊<UITextFieldTextDidChangeNotification>告訴
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) 
     name:@"UITextFieldTextDidChangeNotification" object:myTextField];
//完成監聽辦法
#pragma mark - Notification Method
-(void)textFieldEditChanged:(NSNotification *)obj
{
  UITextField *textField = (UITextField *)obj.object;
  NSString *toBeString = textField.text;

  //獲得高亮部門
  UITextRange *selectedRange = [textField markedTextRange];
  UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];

  // 沒有高亮選擇的字,則對已輸出的文字停止字數統計和限制
  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];
      }
    }
  }
}

小同伴們,明天就分享到這裡,下期更出色!

【值得珍藏的iOS開辟經常使用代碼塊】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved