iOS 小知识总结

2017-04-07  本文已影响38人  木马不在转

1.避免循环引用

8.在导航控制中,或它的子控制器,设置导航栏的标题应该用self.navigationItem.title = @“标题”而不建议self.title = @“标题”;

 9.给cell设置分割线,建议用setFrame:通过设置它高度,设置分割线,而不推荐用给cell底部添加一个高度的UIView,这样做增加了一个控件,从性能上来讲,不如用setFrame设置高度

10.POST请求参数字典的写法,这样比较装逼~
// NSDictionaryOfVariableBindings这个宏生成一个字典,这个宏可以生成一个变量名到变量值映射的Dictionary,比如:
NSNumber * packId=@(2);
NSNumber *userId=@(22);
NSNumber *proxyType=@(2);
NSDictionary *param=NSDictionaryOfVariableBindings(packId,userId,proxyType);
11.去掉cell的分割线左侧15的空隙
- (void)awakeFromNib {
self.separatorInset = UIEdgeInsetsZero;
self.layoutMargins = UIEdgeInsetsZero;
self.preservesSuperviewLayoutMargins = NO;
}
12.手机振动
- (void)vibrate {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
13.定义函数时,希望子类override该方法时候,必须调用super,否则编译器直接报错。
- (void)fooWithNothing attribute((objc_requires_super));
14.误删系统sdk头文件的解决办法
在终端中输入:
$ cd ~/Library/Developer/Xcode/DerivedData/ModuleCache/
$ rm -rf *
15.NS_ASSUME_NONNULL_BEGIN && NS_ASSUME_NONNULL_END

__kindof 这修饰符还是很实用的,解决了一个长期以来的小痛点,拿原来的 UITableView 的这个方法来说:
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
既明确表明了返回值,又让使用者不必写强转。
19.UITableView的plain样式下,取消区头停滞效果

      - (void)scrollViewDidScroll:(UIScrollView *)scrollView
       {
        CGFloat sectionHeaderHeight = sectionHead.height;
        if (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);
       }
      }

20.取图片某一像素点的颜色 在UIImage的分类中

       - (UIColor *)colorAtPixel:(CGPoint)point
        {
             if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point))
          {
             return nil;
           }

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        int bytesPerPixel = 4;
        int bytesPerRow = bytesPerPixel * 1;
        NSUInteger bitsPerComponent = 8;
        unsigned char pixelData[4] = {0, 0, 0, 0};

        CGContextRef context = CGBitmapContextCreate(pixelData,
                                             1,
                                             1,
                                             bitsPerComponent,
                                             bytesPerRow,
                                             colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
      CGColorSpaceRelease(colorSpace);
      CGContextSetBlendMode(context, kCGBlendModeCopy);

      CGContextTranslateCTM(context, -point.x, point.y - self.size.height);
      CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), self.CGImage);
      CGContextRelease(context);

      CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
      CGFloat green = (CGFloat)pixelData[1] / 255.0f;
      CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
      CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

      return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
      }

21.禁止锁屏

      [UIApplication sharedApplication].idleTimerDisabled = YES;
      或
      [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

22.字符串按多个符号分割



23.iOS跳转到App Store下载应用评分

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

24.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);

25.Base64编码与NSString对象或NSData对象的转换

      NSData *nsdata = [@"iOS Developer Tips encoded in Base64"dataUsingEncoding:NSUTF8StringEncoding];

      NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];

      NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];

      NSString *base64Decoded = [[NSString alloc]  initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];

26.取消UICollectionView的隐式动画UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。

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

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

27.dispatch_group的使用 主要用于多任务请求

      dispatch_group_t dispatchGroup = dispatch_group_create();
      dispatch_group_enter(dispatchGroup);
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"第一个请求完成");
      dispatch_group_leave(dispatchGroup);
      });

      dispatch_group_enter(dispatchGroup);

      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       NSLog(@"第二个请求完成");
      dispatch_group_leave(dispatchGroup);
      });

      dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
        NSLog(@"请求完成");
      });

28.获取手机安装的应用

      Class c =NSClassFromString(@"LSApplicationWorkspace");
      id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
      NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
      for (id item in array)
      {
       NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
      //NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
      NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
      NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
      }

29.应用内打开系统设置界面

      //iOS8之后
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
      //如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。

30.navigationBar根据滑动距离的渐变色实现

      - (void)scrollViewDidScroll:(UIScrollView *)scrollView
      {
        CGFloat offsetToShow = 200.0;//滑动多少就完全显示
        CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
        [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;
      }

31.AFN移除JSON中的NSNull

      AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
      response.removesKeysWithNullValues = YES;

32.UIWebView里面的图片自适应屏幕

      - (void)webViewDidFinishLoad:(UIWebView *)webView
       {
         NSString *js = @"function imgAutoFit() { \
         var imgs = document.getElementsByTagName('img'); \
         for (var i = 0; i ( imgs.length; ++i) { \
         var img = imgs[i]; \
          img.style.maxWidth = %f; \
        } \
       }";

      js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];

        [webView stringByEvaluatingJavaScriptFromString:js];
        [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
      }

上一篇下一篇

猜你喜欢

热点阅读