值得收藏的iOS开发常用代码块

2020-01-18 16:10:45丽君

字符串反转


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