美文网首页
iOS开发小技巧总结(转载)

iOS开发小技巧总结(转载)

作者: lucienlong | 来源:发表于2018-10-12 09:47 被阅读0次

    1.打印 View 所有子视图:

    po [[self view]recursiveDescription]
    

    2.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];
    

    3.播放声音:

    //  1. 获取音效资源的路径
     NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
     //  2. 将路劲转化为 url
     NSURL *tempUrl = [NSURL fileURLWithPath:path];
     //  3. 用转化成的 url 创建一个播放器
     NSError *error = nil;
     AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
     self.player = play;
     //  4. 播放
     [play play];
    

    4.修改 UITextField 中 Placeholder 的文字颜色:

    [text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    

    5.判断 view 是不是指定视图的子视图:

    BOOL isView =  [textView isDescendantOfView:self.view];
    

    6.判断对象是否遵循了某协议:

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

    7.系统键盘通知消息:

    1、UIKeyboardWillShowNotification- 将要弹出键盘
    2、UIKeyboardDidShowNotification- 显示键盘
    3、UIKeyboardWillHideNotification- 将要隐藏键盘
    4、UIKeyboardDidHideNotification- 键盘已经隐藏
    5、UIKeyboardWillChangeFrameNotification- 键盘将要改变 frame
    6、UIKeyboardDidChangeFrameNotification- 键盘已经改变 frame
    

    8.关闭 navigationController 的滑动返回手势:

    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    

    9.设置状态栏背景为任意的颜色:

    -(void)setStatusColor
    {
        UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
        statusBarView.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:statusBarView];
    }
    

    10.Label 行间距:

    -(void)test
    {
        NSMutableAttributedString *attributedString =
       [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
        NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];
       [paragraphStyle setLineSpacing:3];
    
        // 调整行间距
       [attributedString addAttribute:NSParagraphStyleAttributeName
                             value:paragraphStyle
                             range:NSMakeRange(0, [self.contentLabel.text length])];
         self.contentLabel.attributedText = attributedString;
    }
    

    11.UIImageView 填充模式:

    @"UIViewContentModeScaleToFill",      // 拉伸自适应填满整个视图
    @"UIViewContentModeScaleAspectFit",   // 自适应比例大小显示
    @"UIViewContentModeScaleAspectFill",  // 原始大小显示
    @"UIViewContentModeRedraw",           // 尺寸改变时重绘
    @"UIViewContentModeCenter",           // 中间
    @"UIViewContentModeTop",              // 顶部
    @"UIViewContentModeBottom",           // 底部
    @"UIViewContentModeLeft",             // 中间贴左
    @"UIViewContentModeRight",            // 中间贴右
    @"UIViewContentModeTopLeft",          // 贴左上
    @"UIViewContentModeTopRight",         // 贴右上
    @"UIViewContentModeBottomLeft",       // 贴左下
    @"UIViewContentModeBottomRight",      // 贴右下
    

    12.iOS 中的一些手势:

    轻击手势(TapGestureRecognizer)
    轻扫手势(SwipeGestureRecognizer)
    长按手势(LongPressGestureRecognizer)
    拖动手势(PanGestureRecognizer)
    捏合手势(PinchGestureRecognizer)
    旋转手势(RotationGestureRecognizer)
    

    13.字符串去除所有的空格:

    [str stringByReplacingOccurrencesOfString:@" " withString:@""]
    

    14.字符串去除首尾的空格:

    [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    

    15.数组的排序(升序、降序及乱序):

    #pragma mark -- 数组排序方法(升序)
    - (void)arraySortASC {
    
    //定义一个数字数组
    //    NSArray *array = @[@"B",@"E",@"A",@"D",@"C"];
    //对数组进行排序
    NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        return [obj1 compare:obj2]; //升序
    }];
    NSLog(@"result=%@",result);
    }
    
    #pragma mark -- 数组排序方法(降序)
    - (void)arraySortDESC{
    //定义一个数字数组
    NSArray *array = @[@(3),@(4),@(2),@(1)];
    //对数组进行排序
    NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        return [obj2 compare:obj1]; //降序
    }];
    NSLog(@"result=%@",result);
    }
    
    #pragma mark -- 数组排序方法(乱序)
    - (void)arraySortBreak{
    //定义一个数字数组
    NSArray *array = @[@(3),@(4),@(2),@(1),@(5),@(6),@(0)];
    //对数组进行排序
    NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSLog(@"%@~%@",obj1,obj2);
        //乱序
        if (arc4random_uniform(2) == 0) {
            return [obj2 compare:obj1]; //降序
        }
        else{
            return [obj1 compare:obj2]; //升序
        }
    }];
    NSLog(@"result=%@",result);
    }
    

    16.解决ios11的下移问题:

    //解决ios11的下移问题
    if ([_YDHomeTableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) 
    {  
        if (@available(iOS 11.0, *)) 
        {          
          _YDHomeTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } 
        else  {}   
    }
    

    17.获取子视图所在的父视图:

    -(UIViewController *)getViewController
    {
        UIViewController *VC = nil;
        UIResponder *responder = self.nextResponder;
        while (responder) {
            if ([responder isKindOfClass:[UIViewController class]]) {
                VC = (UIViewController *)responder;
                break;
            }
            responder = responder.nextResponder;
        }
        return VC;
    }
    

    18.iOS获取汉字的拼音:

    +(NSString *)transform:(NSString *)chinese
    {    
        //将NSString装换成NSMutableString 
        NSMutableString *pinyin = [chinese mutableCopy];    
        //将汉字转换为拼音(带音标)    
        CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);    
        NSLog(@"%@", pinyin);    
        //去掉拼音的音标    
        CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);    
        NSLog(@"%@", pinyin);    
        //返回最近结果    
        return pinyin;
     }
    

    19.改变UITableViewHeaderFooterView的背景色:

    -(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithReuseIdentifier:reuseIdentifier];
        if (self) {
            [self.contentView setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.5]];
            self.backgroundView = ({
                UIView * view = [[UIView alloc] initWithFrame:self.bounds];
                view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
                view;
            });
        }
        return self;
    }
    

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

    // Create NSData object
    NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
      dataUsingEncoding:NSUTF8StringEncoding];
    
    // Get NSString from NSData object in Base64
    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
    
    // Print the Base64 encoded string
    NSLog(@"Encoded: %@", base64Encoded);
    
    // Let's go the other way...
    
    // NSData from the Base64 encoded str
    NSData *nsdataFromBase64String = [[NSData alloc]
      initWithBase64EncodedString:base64Encoded options:0];
    
    // Decoded NSString from the NSData
    NSString *base64Decoded = [[NSString alloc]
      initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    NSLog(@"Decoded: %@", base64Decoded);
    

    21.UIImage 占用内存大小:

    UIImage *image = [UIImage imageNamed:@"aa"];
    NSUInteger size  = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
    

    22.GCD timer定时器:

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(timer, ^{
        //@"倒计时结束,关闭"
        dispatch_source_cancel(timer); 
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    });
    dispatch_resume(timer);
    

    23.计算文件大小:

    //文件大小
    - (long long)fileSizeAtPath:(NSString *)path
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:path])
        {
            long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
            return size;
        }
        return 0;
    }
    
    //文件夹大小
    - (long long)folderSizeAtPath:(NSString *)path
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        long long folderSize = 0;
        if ([fileManager fileExistsAtPath:path])
        {
            NSArray *childerFiles = [fileManager subpathsAtPath:path];
            for (NSString *fileName in childerFiles)
            {
                NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
                if ([fileManager fileExistsAtPath:fileAbsolutePath])
                {
                    long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;
                    folderSize += size;
                }
            }
        }
        return folderSize;
    }
    

    24.字符串中是否含有中文:

    +(BOOL)checkIsChinese:(NSString *)string
    {
        for (int i=0; i<string.length; i++)
        {
            unichar ch = [string characterAtIndex:i];
            if (0x4E00 <= ch  && ch <= 0x9FA5)
            {
                return YES;
            }
        }
        return NO;
    }
    

    25.禁止手机睡眠:

    [UIApplication sharedApplication].idleTimerDisabled = YES;
    

    26.去除数组中重复的对象:

    NSArray *newArr = [oldArr valueForKeyPath:@"distinctUnionOfObjects.self"];
    

    27.给view截图:

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    28.获取window的方法:

    +(UIWindow*)getWindow 
    {
        UIWindow* win = nil; //[UIApplication sharedApplication].keyWindow;
        for (id item in [UIApplication sharedApplication].windows) {
            if ([item class] == [UIWindow class]) {
                if (!((UIWindow*)item).hidden) {
                    win = item;
                    break;
                }
            }
        }
        return win;
    }
    

    29.获取app缓存大小:

    -(CGFloat)getCachSize 
    {
        NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
        //获取自定义缓存大小
        //用枚举器遍历 一个文件夹的内容
        //1.获取 文件夹枚举器
        NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
        NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
        __block NSUInteger count = 0;
        //2.遍历
        for (NSString *fileName in enumerator) {
            NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
            NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
            count += fileDict.fileSize;//自定义所有缓存大小
        }
        // 得到是字节  转化为M
        CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
        return totalSize;
    }
    

    30.清理app缓存:

    - (void)handleClearView 
    {
        //删除两部分
        //1.删除 sd 图片缓存
        //先清除内存中的图片缓存
        [[SDImageCache sharedImageCache] clearMemory];
        //清除磁盘的缓存
        [[SDImageCache sharedImageCache] clearDisk];
        //2.删除自己缓存
        NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
        [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
    }
    

    31.判断图片类型:

    //通过图片Data数据第一个字节 来获取图片扩展名
    -(NSString *)contentTypeForImageData:(NSData *)data
    {
        uint8_t c;
        [data getBytes:&c length:1];
        switch (c)
        {
            case 0xFF:
                return @"jpeg";
            case 0x89:
                return @"png";
            case 0x47:
                return @"gif";
            case 0x49:
            case 0x4D:
                return @"tiff";
            case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"]
                && [testString hasSuffix:@"WEBP"])
            {
                return @"webp";
            }
            return nil;
        }
        return nil;
    }
    

    32.圆形图片:

    -(instancetype)circleImage
    {
        // 开启图形上下文
        UIGraphicsBeginImageContext(self.size);
        // 获得上下文
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        // 矩形框
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        // 添加一个圆
        CGContextAddEllipseInRect(ctx, rect);
        // 裁剪(裁剪成刚才添加的图形形状)
        CGContextClip(ctx);
        // 往圆上面画一张图片
        [self drawInRect:rect];
        // 获得上下文中的图片
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        // 关闭图形上下文
        UIGraphicsEndImageContext();
        return image;
    }
    

    33.验证身份证号:

    -(BOOL)validateIdentityCard 
    {
        BOOL flag;
        if (self.length <= 0) 
        {
            flag = NO;
            return flag;
        }
        NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
        NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
        return [identityCardPredicate evaluateWithObject:self];
    }
    

    34.给imageView添加倒影:

    CGRect frame = self.frame;
    frame.origin.y += (frame.size.height + 1);
    
    UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame];
    self.clipsToBounds = TRUE;
    reflectionImageView.contentMode = self.contentMode;
    [reflectionImageView setImage:self.image];
    reflectionImageView.transform = CGAffineTransformMakeScale(1.0, -1.0);
    
    CALayer *reflectionLayer = [reflectionImageView layer];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.bounds = reflectionLayer.bounds;
    gradientLayer.position = CGPointMake(reflectionLayer.bounds.size.width / 2, reflectionLayer.bounds.size.height * 0.5);
    gradientLayer.colors = [NSArray arrayWithObjects:
                            (id)[[UIColor clearColor] CGColor],
                            (id)[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] CGColor], nil];
    
    gradientLayer.startPoint = CGPointMake(0.5,0.5);
    gradientLayer.endPoint = CGPointMake(0.5,1.0);
    reflectionLayer.mask = gradientLayer;
    
    [self.superview addSubview:reflectionImageView];
    

    35.获取视频的第一帧图片:

    NSURL *url = [NSURL URLWithString:filepath];
    AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
    generate1.appliesPreferredTrackTransform = YES;
    NSError *err = NULL;
    CMTime time = CMTimeMake(1, 2);
    CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
    UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
    return one;
    

    36.删除UIButton的所有点击事件:

    [testButton removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
    

    37.删除某个view所有的子视图:

    [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
    

    38.UITextView中打开或禁用复制,剪切,选择,全选等功能:

    // 继承UITextView重写这个方法
    -(BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
    // 返回NO为禁用,YES为开启
        // 粘贴
        if (action == @selector(paste:)) return NO;
        // 剪切
        if (action == @selector(cut:)) return NO;
        // 复制
        if (action == @selector(copy:)) return NO;
        // 选择
        if (action == @selector(select:)) return NO;
        // 选中全部
        if (action == @selector(selectAll:)) return NO;
        // 删除
        if (action == @selector(delete:)) return NO;
        // 分享
        if (action == @selector(share)) return NO;
        return [super canPerformAction:action withSender:sender];
    }
    

    39.字符串反转:

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

    40.UIView设置部分圆角(左上,右上,左下,右下):

    CGRect rect = view.bounds;
    CGSize radio = CGSizeMake(30, 30);//圆角尺寸
    UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//这是圆角位置
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
    CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//创建shapelayer
    masklayer.frame = view.bounds;
    masklayer.path = path.CGPath;//设置路径
    view.layer.mask = masklayer;
    

    41.禁用emoji:

    - (NSString *)disable_emoji:(NSString *)text
    {
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
        NSString *modifiedString = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];
        return modifiedString;
    }
    

    42.UIAlertController颜色字号更改:

    NSMutableAttributedString *attTitle = [[NSMutableAttributedString alloc]initWithString:@"标题1" attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:[UIFont systemFontOfSize:17]}];
    NSMutableAttributedString *attMessage = [[NSMutableAttributedString alloc]initWithString:@"message" attributes:@{NSForegroundColorAttributeName:[UIColor purpleColor],NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    
    UIAlertController *action = [UIAlertController alertControllerWithTitle:@"标题1" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];
    [action setValue:attTitle forKey:@"attributedTitle"];
    [action setValue:attMessage forKey:@"attributedMessage"];
    
    UIAlertAction *alert1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadCamera];
    }];
    [alert1 setValue:[UIColor cyanColor] forKey:@"titleTextColor"];
    [action addAction:alert1];
    
    UIAlertAction *alert2 = [UIAlertAction actionWithTitle:@"从相册选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadPhotoLibraryPhoto];
    }];
    [alert2 setValue:[UIColor brownColor] forKey:@"titleTextColor"];
    [action addAction:alert2];
    
    UIAlertAction *cancelAlert = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [cancelAlert setValue:[UIColor redColor] forKey:@"titleTextColor"];
    [action addAction:cancelAlert];
    [self presentViewController:action animated:YES completion:nil];
    

    43.UILabel下划线:

    UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 120, 200, 30)];
    testLabel.backgroundColor = [UIColor lightGrayColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    NSString *cstrTitle = @"This is an attributed string.下划线";
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:cstrTitle attributes:attribtDic];
    testLabel.attributedText = attribtStr;
    [self.view addSubview:testLabel];
    

    44.view添加虚线边框:

    CAShapeLayer *border = [CAShapeLayer layer];
    border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
    border.fillColor = nil;
    border.lineDashPattern = @[@4, @2];
    border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
    border.frame = view.bounds;
    [view.layer addSublayer:border];
    

    45.UIImage和base64互转:

    -(NSString *)encodeToBase64String:(UIImage *)image {
     return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    }
     
    -(UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
      NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
      return [UIImage imageWithData:data];
    }
    

    46.UILabel显示不同颜色字体和行间距:

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:label.text];
    //行间距
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:20];
    [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, label.text.length)];
    //不同颜色
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
    label.attributedText = attrString;
    

    47.判断一个字符串是否为数字:

    NSString *testString = @"123wo";
    NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([testString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
    {
        // 是数字
    } else
    {
        // 不是数字
    }
    

    48.获取当前导航控制器下前一个控制器:

    -(UIViewController *)backViewController
    {
        NSInteger myIndex = [self.navigationController.viewControllers indexOfObject:self];
     
        if ( myIndex != 0 && myIndex != NSNotFound ) {
            return [self.navigationController.viewControllers objectAtIndex:myIndex-1];
        } else {
            return nil;
        }
    }
    

    49.让导航控制器pop回指定的控制器:

    NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
    for (UIViewController *subVC in allViewControllers) {
        if ([subVC isKindOfClass:[CommunityViewController class]]) {
            [self.navigationController popToViewController:subVC animated:NO];
        }
    }
    

    50.UIWebView添加单击手势不响应:

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewClick)];
    tap.delegate = self;
    [self.webView addGestureRecognizer:tap];
    //因为webView本身有一个单击手势,所以再添加会造成手势冲突,从而不响应。需要绑定手势代理,遵循UIGestureRecognizerDelegate并实现下边的代理方法
    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
        return YES;
    }
    

    51.设置UITextField光标位置:

    //index要设置的光标位置
    -(void)cursorLocation:(UITextField *)textField index:(NSInteger)index
    {
        NSRange range = NSMakeRange(index, 0);
        UITextPosition *start = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location];
        UITextPosition *end = [textField positionFromPosition:start offset:range.length];
        [textField setSelectedTextRange:[textField textRangeFromPosition:start toPosition:end]];
    }
    

    52.去除webView黑底:

    [webView setBackgroundColor:[UIColor clearColor]];
    [webView setOpaque:NO];
    for (UIView *subView in [webView subviews])
    {
        if ([subView isKindOfClass:[UIScrollView class]])
        {
            for (UIView *v2 in subView.subviews)
            {
                if ([v2 isKindOfClass:[UIImageView class]])
                {
                    v2.hidden = YES;
                }
            }
        }
    }
    

    53.解决openUrl延时问题:

    //方法一
    dispatch_async(dispatch_get_main_queue(), ^{
         UIApplication *application = [UIApplication sharedApplication];
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:URL options:@{}
               completionHandler:nil];
        } else {
            [application openURL:URL];
        }
    });
    // 方法二
    [self performSelector:@selector(redirectToURL:) withObject:url afterDelay:0.1];
    -(void)redirectToURL
    {
        UIApplication *application = [UIApplication sharedApplication];
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:URL options:@{}
               completionHandler:nil];
        } else {
            [application openURL:URL];
        }
    }
    

    54.UITextField 只能输入数字和字母:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textFieldChanged:)
                                                     name:UITextFieldTextDidChangeNotification
                                                   object:nil];
    监听name:UITextFieldTextDidChangeNotification 和  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 来实现。
    - (BOOL)validatePasswordString:(NSString *)resultMStr
    {
        BOOL result = YES;
        switch (self.mode) {
            case HXSChangePasswordLogin: {
                NSString *regex = @"^[a-zA-Z0-9]+$";
                NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
                result = [pred evaluateWithObject:resultMStr];
                break;
            }
    
            case HXSChangePasswordPay: {
                NSString *regex = @"^[0-9]+$";
                NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
                result = [pred evaluateWithObject:resultMStr];
                break;
            }
        }
    
        return result;
    }
    

    55.退出app:

    - (void)exitApplication{
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        
        [UIView animateWithDuration:0.5f animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
        } completion:^(BOOL finished) {
            exit(0);
        }];
    }
    

    56.返回当前星期几:

    - (NSString*)toWeekString
    {
        static NSCalendar *calendar;
        if (calendar == nil) {
            calendar =
            [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        }
        unsigned unitFlags = NSWeekdayCalendarUnit;
        NSDateComponents *comps = [calendar components:unitFlags fromDate:self];
        NSArray *weekArr =
        [NSArray arrayWithObjects:@"日",@"一",@"二",@"三",@"四",@"五",@"六", nil];
        
        return [NSString stringWithFormat:@"星期%@",
                [weekArr objectAtIndex:[comps weekday]-1]];
    }
    

    57.tableview中隐藏没有内容的cell:

    self.tableView.tableFooterView = [[UIView alloc] init];
    

    58.像Safari一样滑动时隐藏navigationbar:

    self.navigationController.hidesBarsOnSwipe = YES;
    

    59.ScrollView莫名其妙不能在viewController划到顶:

    self.automaticallyAdjustsScrollViewInsets = NO; 
    

    60.点击self.view就让键盘收起:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    {  
       [self.view endEditing:YES];
    }
    

    61.用UIImagePickerController会导致我的statusbar的样式变成黑色:

    -(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated 
    { 
       [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    

    62.navigationbar变成透明的而不是带模糊的效果:

    [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; 
    self.navigationBar.shadowImage = [UIImage new]; 
    self.navigationBar.translucent = YES;
    

    63.改变uitextfield placeholder的颜色和位置:

    -(void) drawPlaceholderInRect:(CGRect)rect 
    {  
      [[UIColor blueColor] setFill]; 
      [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment]; 
    }
    

    64.左右抖动动画:

    //1.创建核心动画
    CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animation];  
    //2.告诉系统执行什么动画。
    keyAnima.keyPath = @"transform.rotation"; keyAnima.values = @[@(-M_PI_4 /90.0 * 5),@(M_PI_4 /90.0 * 5),@(-M_PI_4 /90.0 * 5)];  
    //3.执行完之后不删除动画
    keyAnima.removedOnCompletion = NO;  
    //4.执行完之后保存最新的状态
    keyAnima.fillMode = kCAFillModeForwards;  
    //5.动画执行时间
    keyAnima.duration = 0.2;  
    //6.设置重复次数。
    keyAnima.repeatCount = MAXFLOAT;  
    //7.添加核心动画
    [self.iconView.layer addAnimation:keyAnima forKey:nil];
    

    65.屏幕截图:

    //1.开启一个与图片相关的图形上下文 
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);  
    //2.获取当前图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();  
    //3.获取需要截取的view的layer 
    [self.view.layer renderInContext:ctx];  
    //4.从当前上下文中获取图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
    //5.关闭图形上下文 
    UIGraphicsEndImageContext();  
    //6.把图片保存到相册 
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    

    66.强制横屏:

    #pragma mark - 强制横屏代码
    -(BOOL)shouldAutorotate
    {  
       //是否支持转屏  
       return NO;
    }
     
    -(UIInterfaceOrientationMask)supportedInterfaceOrientations
    {  
       //支持哪些转屏方向  
       return UIInterfaceOrientationMaskLandscape;
    }
     
    -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
    {  
       return UIInterfaceOrientationLandscapeRight;
    }
    
    -(BOOL)prefersStatusBarHidden
    {  
       return NO;
    }
    

    67.应用程序的生命周期:

    //1.启动但还没进入状态保存 :
     -(BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
    //2.基本完成程序准备开始运行:
     -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    //3.当应用程序将要入非活动状态执行,应用程序不接收消息或事件,比如来电话了:
     -(void)applicationWillResignActive:(UIApplication *)application  
    //4.当应用程序入活动状态执行,这个刚好跟上面那个方法相反:
     -(void)applicationDidBecomeActive:(UIApplication *)application  
    //5.当程序被推送到后台的时候调用。所以要设置后台继续运行,则在这个函数里面设置即可:
     -(void)applicationDidEnterBackground:(UIApplication *)application 
    //6.当程序从后台将要重新回到前台时候调用,这个刚好跟上面的那个方法相反:
     -(void)applicationWillEnterForeground:(UIApplication *)application  
    //7.当程序将要退出是被调用,通常是用来保存数据和一些退出前的清理工作:
     -(void)applicationWillTerminate:(UIApplication *)application
    

    68.视图的生命周期:

    1. alloc 创建对象,分配空间
    2. init (initWithNibName) 初始化对象,初始化数据
    3. loadView 从nib载入视图 ,除非你没有使用xib文件创建视图
    4. viewDidLoad 载入完成,可以进行自定义数据以及动态创建其他控件
    5. viewWillAppear视图将出现在屏幕之前,马上这个视图就会被展现在屏幕上了
    6. viewDidAppear 视图已在屏幕上渲染完成
    7. viewWillDisappear 视图将被从屏幕上移除之前执行
    8. viewDidDisappear 视图已经被从屏幕上移除,用户看不到这个视图了
    9. dealloc 视图被销毁,此处需要对你在init和viewDidLoad中创建的对象进行释放
       viewVillUnload- 当内存过低,即将释放时调用;viewDidUnload-当内存过低,释放一些不需要的视图时调用。
    

    69.设置按钮字体居右:

    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    

    70.单选:

    -(void)ButtonAction:(UIButton*)btn 
    {
           NSPredicate*pre = [NSPredicatepredicateWithFormat:@"SELF.isSelected == YES"];
           NSArray *selectArray = [_buttonArrayfilteredArrayUsingPredicate:pre];
      [selectArrayenumerateObjectsUsingBlock:^(UIButton*_Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
               obj.selected=NO;
               obj.backgroundColor= [UIColorwhiteColor];
               obj.layer.borderColor=SAColorByRGB(235,235,235).CGColor;
           }];
           btn.selected=YES;
    }
    

    71.label字体自适应:

    label.adjustsFontSizeToFitWidth = YES;
    

    72.注册截屏通知:

    [[NSNotificationCenterdefaultCenter]addObserver:self selector:@selector(userDidTakeScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    //截屏响应
    -(void)userDidTakeScreenshot:(NSNotification*)notification 
    {
     [selfperformSelector:@selector(showNotification)withObject:nilafterDelay:0.5];
    }
    -(void)showNotification 
    {
     [SANotificationViewshowNotificationViewWithContent:NSLocalizedString(@"已截屏,是要吐槽么?",nil)type:SANotificationViewTypeScreenShotsdidClick:nil];
    }
    

    73.取消searchbar背景色:

    -(UISearchBar*)searchBar
    {
       if(!_searchBar) {
          _searchBar= [[UISearchBaralloc]init];
          _searchBar.backgroundImage= [selfimageWithColor:[UIColorclearColor]size:CGSizeMake(4,4)];
          _searchBar.barStyle=UIBarStyleDefault;
          _searchBar.layer.cornerRadius=5;
          _searchBar.clipsToBounds=YES;
          _searchBar.backgroundColor=SAColorByRGB(243.0,243.0,243.0);
          _searchBar.placeholder=NSLocalizedString(@"搜索",nil);
          
          UITextField*field = [_searchBarvalueForKey:@"_searchField"];
          field.backgroundColor=SAColorByRGB(243.0,243.0,243.0);
          field.textColor=SAColorByRGB(51.0,51.0,51.0);
          field.font= [UIFontsystemFontOfSize:12];
       
          UIImage*image = [UIImageimageNamed:@"icon_search"];
          UIImageView*iconView = [[UIImageViewalloc]initWithImage:image];
          iconView.contentMode=UIViewContentModeCenter;
          iconView.frame=CGRectMake(0,0, image.size.width,28);
          field.leftView= iconView;
       [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(didChange:)name:UITextFieldTextDidChangeNotificationobject:nil];
    }
       return_searchBar;
    }
    
    -(UIImage*)imageWithColor:(UIColor*)color size:(CGSize)size 
    {
        CGRectrect = CGRectMake(0,0, size.width, size.height);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRefcontext = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [colorCGColor]);
        CGContextFillRect(context, rect);
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    

    74.判断手机号:

    NSString *phoneRegex = @"(\\\\+\\\\d+)?1[34578]\\\\d{9}$";
    NSPredicate *phoneTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTestevaluateWithObject:string];
    

    75.判断邮箱:

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,4}";
    

    76.改变图片透明度:

    -(UIImage*)sa_imageWithAlpha:(CGFloat)alpha 
    {
       if(alpha>1.0) {
         alpha =1.0;
       }
    
       if(alpha<=0.0) {
         alpha =0.0;
       }
       UIGraphicsBeginImageContextWithOptions(self.size,NO,0.0f);
       CGContextRefctx =UIGraphicsGetCurrentContext();
       CGRectarea =CGRectMake(0,0,self.size.width,self.size.height);
       CGContextScaleCTM(ctx,1, -1);
       CGContextTranslateCTM(ctx,0, -area.size.height);
       CGContextSetBlendMode(ctx,kCGBlendModeMultiply);
       CGContextSetAlpha(ctx, alpha);
       CGContextDrawImage(ctx, area,self.CGImage);
       UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return newImage;
    }
    

    77.任意改变图片尺寸:

    -(UIImage*)sa_imageWithSize:(CGSize)size
    {
       UIGraphicsBeginImageContext(CGSizeMake(size.width, size.height));
       [selfdrawInRect:CGRectMake(0,0, size.width, size.height)];
       UIImage*resizedImage =UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return resizedImage;
    }
    

    78.等比例放缩图片:

    -(UIImage*)sa_imageStretchWithScale:(CGFloat)scale 
    {
       UIGraphicsBeginImageContext(CGSizeMake(self.size.width* scale,self.size.height* scale));
       [selfdrawInRect:CGRectMake(0,0,self.size.width* scale,self.size.height* scale)];
       UIImage*scaledImage =UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return scaledImage;
    }
    

    79.图片压缩(返回NSData 压缩比例0.0~1.0):

    -(NSData*)sa_imageCompressReturnDataWithRatio:(CGFloat)ratio 
    {
    //UIImageJPEGRepresentation和UIImagePNGRepresentation
       if(ratio>1.0) {
         ratio =1.0;
       }
    
       if(ratio<=0) {
       ratio =0.0;
       }
       NSData*compressedData =UIImageJPEGRepresentation(self, ratio);
       return compressedData;
    }
    

    80.图片压缩 (返回UIImage 压缩比例0.0~1.0):

    -(UIImage*)sa_imageCompressReturnImageWithRatio:(CGFloat)ratio {
    //UIImageJPEGRepresentation和UIImagePNGRepresentation
       if(ratio>1.0) {
         ratio =1.0;
       }
    
       if(ratio<=0) {
         ratio =0.0;
       }
       NSData*compressedData =UIImageJPEGRepresentation(self, ratio);
       UIImage*compressedImage = [UIImageimageWithData:compressedData];
       return compressedImage;
    }
    

    81.将UIView转化成图片:

    -(UIImage*)sa_getImageFromView:(UIView*)theView 
    {
    UIGraphicsBeginImageContextWithOptions(theView.bounds.size,YES, theView.layer.contentsScale);
       [theView.layerrenderInContext:UIGraphicsGetCurrentContext()];
       UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return image;
    }
    

    82.两张图片叠加、合成:

    -(UIImage*)sa_integrateImageWithRect:(CGRect)rect andAnotherImage:(UIImage*)anotherImage anotherImageRect:(CGRect)anotherRect integratedImageSize:(CGSize)size 
    {
       UIGraphicsBeginImageContext(size);
       [selfdrawInRect:rect];
       [anotherImagedrawInRect:anotherRect];
       UIImage*integratedImage =UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return integratedImage;
    }
    

    83.图片添加水印:

    /**
    图片添加水印
    @param markImage水印图片
    @param imgRect水印图片对于原图片的rect
    @param alpha水印图片透明度
    @param markStr水印文字
    @param strRect水印文字对于原图片的rect
    @param attribute水印文字的设置颜色、字体大小
    @return添加水印后的图片
    */
    
    -(UIImage*)sa_imageWaterMark:(UIImage*)markImage imageRect:(CGRect)imgRect markImageAlpha:(CGFloat)alpha markString:(NSString*)markStr stringRect:(CGRect)strRect stringAttribute:(NSDictionary*)attribute 
    {
         UIGraphicsBeginImageContext(self.size);
    [selfdrawInRect:CGRectMake(0,0,self.size.width,self.size.height)blendMode:kCGBlendModeNormalalpha:1.0];
    
         if(markImage) 
         {
          [markImagedrawInRect:imgRectblendMode:kCGBlendModeNormalalpha:alpha];  
         }
    
         if(markStr) {
           //UILabel convertto UIImage
           UILabel*markStrLabel = [[UILabelalloc]initWithFrame:CGRectMake(0,0, strRect.size.width,         strRect.size.height)];
           markStrLabel.textAlignment=NSTextAlignmentCenter;
           markStrLabel.numberOfLines=0;
           markStrLabel.attributedText= [[NSAttributedStringalloc]initWithString:markStrattributes:attribute];
           UIImage*image = [selfsa_getImageFromView:markStrLabel];
        [imagedrawInRect:strRectblendMode:kCGBlendModeNormalalpha:1.0];;
     }
         UIImage*waterMarkedImage =UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
         return waterMarkedImage;
    }
    

    84.UITableView的Group样式下顶部空白处理:

    //分组列表头部空白处理
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
    self.tableView.tableHeaderView = view;
    

    85.两种方法删除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];
    }
    

    86.防止scrollView手势覆盖侧滑手势:

    [scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
    

    87.获取到webview的高度:

    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    

    88.WebView长按保存图片:

    加一个长按手势,在响应里:
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];
    

    89.cell右边标志符的颜色改变:

    self.accessoryType = UITableViewCellAccessoryCheckmark;
    self.tintColor = [UIColor colorWithRed:140.0/255.0 green:197.0/255.0  blue:66.0/255.0  alpha:1];
    

    90.设置启动页的时间:

    [NSThread sleepForTimeInterval:3.0];//设置启动页面时间
    

    91.数组元素按字母排序:

        _enStateArr = [_stateDic allKeys];
        _enStateArr = [_enStateArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            NSComparisonResult result = [obj1 compare:obj2];
            return result==NSOrderedDescending;
        }];
    

    92.四舍五入:

    -(float)roundFloat:(float)price
    {
        return (floorf(price*100 + 0.5))/100;
    }
    

    93.红外线感应器的使用(多用于电话接听界面):

      //允许临近检测,物体接近屏幕屏幕变黑且不可操作
      [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    

    94.解决ScrollView滑动卡顿的问题:

         /** 解决scrollView 滑动卡顿问题 */
        [self performSelector:@selector(test1) withObject:nil afterDelay:4 inModes:@[NSDefaultRunLoopMode]];
    

    95.删除重用的cell的所有子视图,从而得到一个没有特殊格式的cell,供其他cell重用:

        if (cell == nil) 
        {   
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];   
        }   
        else   
        {   
            //删除cell的所有子视图   
            while ([cell.contentView.subviews lastObject] != nil)   
            {   
                [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];   
            }   
        }
    

    96.iOS单例创建:

    +(instancetype)shareManager
    {
        static User *user = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            user = [[User alloc] init];
        });
        return user;
    }
    

    97.bounds 和 Frame区别:

    先看到下面的代码你肯定就明白了一些:
    -(CGRect)frame{
        return CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);
    }
    -(CGRect)bounds{
        return CGRectMake(0,0,self.frame.size.width,self.frame.size.height);
    }
    很明显,bounds的原点是(0,0)点(就是view本身的坐标系统,默认永远都是0,0点,除非人为setbounds),而frame的原点却是任意的(相对于父视图中的坐标位置)。
    

    98.设置键盘在tableView滚动的时候消失掉:

    //设置键盘在tableview滚动的时候消失.
    tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    

    99.UILabel修改行距,首行缩进:

    UILabel修改文字行距,首行缩进
    lineSpacing: 行间距
    firstLineHeadIndent:首行缩进
    font: 字体
    textColor: 字体颜色
    -(NSDictionary *)settingAttributesWithLineSpacing:(CGFloat)lineSpacing FirstLineHeadIndent:(CGFloat)firstLineHeadIndent Font:(UIFont *)font TextColor:(UIColor *)textColor
    {
        //分段样式
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        //行间距
        paragraphStyle.lineSpacing = lineSpacing;
        //首行缩进
        paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;
        //富文本样式
        NSDictionary *attributeDic = @{
                                       NSFontAttributeName : font,
                                       NSParagraphStyleAttributeName : paragraphStyle,
                                       NSForegroundColorAttributeName : textColor
                                       };
        return attributeDic;
    }
    

    100.在当前屏幕获取第一响应:

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

    相关文章

      网友评论

          本文标题:iOS开发小技巧总结(转载)

          本文链接:https://www.haomeiwen.com/subject/qadbaftx.html