美文网首页
iOS开发常用代码大全

iOS开发常用代码大全

作者: Arackboss | 来源:发表于2017-09-04 14:24 被阅读0次
    • 判断邮箱格式是否正确的代码
    -(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];
    
    }
    
    • 判断是否有特殊字符
    +(BOOL)isContainsSpecialCharacters:(NSString *)string{
        NSString *regex = @".*[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]+.*";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        
        if ([predicate evaluateWithObject:string]==YES) {
            
            return YES;
            
        }else{
            return NO;
        }
        
    }
    
    • 判断是否包含汉字
    +(BOOL)isChinese:(NSString *)str {
        for(int i=0; i< [str length];i++){
            int a = [str characterAtIndex:i]; if( a > 0x4e00 && a < 0x9fff){
                return YES;
            }
            
        }
        return NO;
    }
    
    • 身份证号码验证
    #pragma mark -身份证号全校验
    + (BOOL)verifyIDCardNumber:(NSString *)IDCardNumber
    {
       IDCardNumber = [IDCardNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
       if ([IDCardNumber length] != 18)
       {
           return NO;
       }
       NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
       NSString *leapMmdd = @"0229";
       NSString *year = @"(19|20)[0-9]{2}";
       NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
       NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
       NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
       NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
       NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
       NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd  , @"[0-9]{3}[0-9Xx]"];
       
       NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
       if (![regexTest evaluateWithObject:IDCardNumber])
       {
           return NO;
       }
       int summary = ([IDCardNumber substringWithRange:NSMakeRange(0,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(10,1)].intValue) *7
       + ([IDCardNumber substringWithRange:NSMakeRange(1,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(11,1)].intValue) *9
       + ([IDCardNumber substringWithRange:NSMakeRange(2,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(12,1)].intValue) *10
       + ([IDCardNumber substringWithRange:NSMakeRange(3,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(13,1)].intValue) *5
       + ([IDCardNumber substringWithRange:NSMakeRange(4,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(14,1)].intValue) *8
       + ([IDCardNumber substringWithRange:NSMakeRange(5,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(15,1)].intValue) *4
       + ([IDCardNumber substringWithRange:NSMakeRange(6,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(16,1)].intValue) *2
       + [IDCardNumber substringWithRange:NSMakeRange(7,1)].intValue *1 + [IDCardNumber substringWithRange:NSMakeRange(8,1)].intValue *6
       + [IDCardNumber substringWithRange:NSMakeRange(9,1)].intValue *3;
       NSInteger remainder = summary % 11;
       NSString *checkBit = @"";
       NSString *checkString = @"10X98765432";
       checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判断校验位
       return [checkBit isEqualToString:[[IDCardNumber substringWithRange:NSMakeRange(17,1)] uppercaseString]];
    }
    
    • 判断字符串是否为空
      +(NSString *)stringIsEmpty:(NSString *)str{

      NSString *string=[NSString stringWithFormat:@"%@",str];

      if ([string isEqualToString:@""]||[string isEqualToString:@"(null)"]||[string isEqualToString:@"<null>"]||string==nil||[string isEqual:[NSNull class]]) {

        string=@"";
      

      }
      return string;
      }

    • 压缩图片

    /**
     *  实现图片的缩小或者放大
     *
     *  @param size  大小范围
     *
     *  @return 新的图片
     */
    -(UIImage*)scaleImageWithSize:(CGSize)size
    {
        UIGraphicsBeginImageContextWithOptions(size,NO,0);  //size 为CGSize类型,即你所需要的图片尺寸
        [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
        UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return scaledImage;   //返回的就是已经改变的图片
    }
    
    • 让网络加载图片有个动画效果(前提是导入了SDWebImage)
    -(void)animationWithImage:(NSString *)imageName
    {
        [self sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image && cacheType == SDImageCacheTypeNone)
            {
                self.alpha = 0;
                [UIView animateWithDuration:0.5 animations:^{
                    
                    self.alpha = 1.0f;
                }];
                
            }
            else
            {
                self.alpha = 1.0f;
            }
        }];
    }
    
    • 根据字符串的长度计算高度
    + (CGSize)sizeWithString:(NSString *)string font:(CGFloat)font maxWidth:(CGFloat)maxWidth
    
    {
        
        NSDictionary *attributesDict = @{NSFontAttributeName:FONT(font)};
        
        CGSize maxSize = CGSizeMake(maxWidth, MAXFLOAT);
        
        CGRect subviewRect = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDict context:nil];
        
        return subviewRect.size;
        
    }
    
    • 拼接属性字符串,在电商类应用用的比较多(比如价格,市场价和销售价,此时可以用一个lable搞定,而不用两个label)
    +(NSAttributedString *)recombinePrice:(CGFloat)CNPrice orderPrice:(CGFloat)unitPrice
    {
        NSMutableAttributedString *mutableAttributeStr = [[NSMutableAttributedString alloc] init];
        NSAttributedString *string1 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%.f",unitPrice] attributes:@{NSForegroundColorAttributeName : [UIColor redColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:12]}];
        NSAttributedString *string2 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%.f",CNPrice] attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:11],NSStrikethroughStyleAttributeName :@(NSUnderlineStyleSingle),NSStrikethroughColorAttributeName : [UIColor lightGrayColor]}];
        [mutableAttributeStr appendAttributedString:string1];
        [mutableAttributeStr appendAttributedString:string2];
        return mutableAttributeStr;
    }
    
    • 调整label行间距
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = lineSpace; // 调整行间距
        NSRange range = NSMakeRange(0, [string length]);
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
        return attributedString;
    }
    
    • 创建导航栏按钮
    + (UIBarButtonItem *)itemWithImageName:(NSString *)imageName highImageName:(NSString *)highImageName target:(id)target action:(SEL)action
    {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:highImageName] forState:UIControlStateHighlighted];
        button.size = button.currentBackgroundImage.size;//按钮的尺寸为按钮的背景图片的尺寸
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        return [[UIBarButtonItem alloc] initWithCustomView:button];
    }
    
    • 数组的安全操作
    - (id)h_safeObjectAtIndex:(NSUInteger)index{
        if(self.count == 0) {
            NSLog(@"--- mutableArray have no objects ---");
            return (nil);
        }
        if(index > MAX(self.count - 1, 0)) {
            NSLog(@"--- index:%li out of mutableArray range ---", (long)index);
            return (nil);
        }
        return ([self objectAtIndex:index]);
    }
    
    • 获取当前时间
    -(NSDate *)getCurrentDate
    {
        NSDate *senddate = [NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *date1 = [dateformatter stringFromDate:senddate];
        return [self stringToDate:date1 withDateFormat:@"YYYY-MM-dd HH:mm:ss"];
     
    }
    
    • 比较两个时间的大小
    -(int)compareDate:(NSDate*)date01 withDate:(NSDate*)date02{
        int ci;
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSComparisonResult result = [date01 compare:date02];
        switch (result)
        {
                //date02比date01大
            case NSOrderedAscending: ci=1; break;
                //date02比date01小
            case NSOrderedDescending: ci=-1; break;
                //date02=date01
            case NSOrderedSame: ci=0; break;
            default: NSLog(@"erorr dates %@, %@", date01, date02); break;
        }
        return ci;
    }
    
    • 日期格式转字符串
    //日期格式转字符串
    - (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format
    {
           NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
       [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
       [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8 * 3600]];
       NSString *strDate = [dateFormatter stringFromDate:date];
       
       return strDate;
    }
    
    • 字符串转日期格式
    - (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
    {
       NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8 * 3600]];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *retdate = [dateFormatter dateFromString:dateString];
        return retdate;
    }
    
    • 将世界时间转化为中国区时间
    - (NSDate *)worldTimeToChinaTime:(NSDate *)date
    {
        NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
        NSInteger interval = [timeZone secondsFromGMTForDate:date];
        NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
        return localeDate;
    }
    
    • 传入今天的时间,返回明天的时间
    //传入今天的时间,返回明天的时间
    - (NSString *)GetTomorrowDay:(NSDate *)aDate {
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
        [components setDay:([components day]+1)];
        
        NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
        NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
        [dateday setDateFormat:@"yyyy-MM-dd"];
        return [dateday stringFromDate:beginningOfWeek];
    }
    
    • 字符串MD5加密
    /** MD5加密得到sign字符串*/
    +(NSString *) md5String:(NSString *) input {
            const char *cStr = [input UTF8String];
        unsigned char digest[CC_MD5_DIGEST_LENGTH];
        CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call
        
        NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
        
        for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
            [output appendFormat:@"%02x", digest[i]];
        return  output;
    }
    
    • 字符串base64加密
    + (NSString *)base64StringFromText:(NSString *)text
    {
        if (text && ![text isEqualToString:LocalStr_None]) {
            //取项目的bundleIdentifier作为KEY  改动了此处
            //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
            NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
            //IOS 自带DES加密 Begin  改动了此处
            //data = [self DESEncrypt:data WithKey:key];
            //IOS 自带DES加密 End
            return [self base64EncodedStringFrom:data];
        }
        else {
            return LocalStr_None;
        }
    }
    
    • base64解密字符串
    /** 解密 */
    + (NSString *)textFromBase64String:(NSString *)base64
    {
        if (base64 && ![base64 isEqualToString:LocalStr_None]) {
            //取项目的bundleIdentifier作为KEY   改动了此处
            //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
            NSData *data = [self dataWithBase64EncodedString:base64];
            //IOS 自带DES解密 Begin    改动了此处
            //data = [self DESDecrypt:data WithKey:key];
            //IOS 自带DES加密 End
            return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
        else {
            return LocalStr_None;
        }
    }
    
    • 字符串反转
    **字符串反转**
    //第一种:
    - (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;
    }
    
    • tableView刷新指定行
    [tabelView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:IndexPath.row inSection:IndexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
    
    • tableView刷新指定组
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];    
    [tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];  
    
    • 将十六进制颜色转换为 UIColor 对象
    + (UIColor *)colorWithHexString:(NSString *)color{
        NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
        // String should be 6 or 8 characters
        if ([cString length] < 6) {
            return [UIColor clearColor];
        }
        // strip "0X" or "#" if it appears
        if ([cString hasPrefix:@"0X"])
            cString = [cString substringFromIndex:2];
        if ([cString hasPrefix:@"#"])
            cString = [cString substringFromIndex:1];
        if ([cString length] != 6)
            return [UIColor clearColor];
        // Separate into r, g, b substrings
        NSRange range;
        range.location = 0;
        range.length = 2;
        //r
        NSString *rString = [cString substringWithRange:range];
        //g
        range.location = 2;
        NSString *gString = [cString substringWithRange:range];
        //b
        range.location = 4;
        NSString *bString = [cString substringWithRange:range];
        // Scan values
        unsigned int r, g, b;
        [[NSScanner scannerWithString:rString] scanHexInt:&r];
        [[NSScanner scannerWithString:gString] scanHexInt:&g];
        [[NSScanner scannerWithString:bString] scanHexInt:&b];
        return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
    }
    
    • 全屏截图
    + (UIImage *)shotScreen{
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIGraphicsBeginImageContext(window.bounds.size);
        [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    
    • 截取view中某个区域生成一张图片
    + (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
        CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
        UIGraphicsBeginImageContext(scope.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
        CGContextTranslateCTM(context, 0, rect.size.height);//下移
        CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
        CGContextDrawImage(context, rect, imageRef);
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        CGImageRelease(imageRef);
        CGContextRelease(context);
        return image;
    }
    
    • 给Image加圆角
    给UIImage添加生成圆角图片的扩展API:  
    - (UIImage *)imageWithCornerRadius:(CGFloat)radius {  
      CGRect rect = (CGRect){0.f, 0.f, self.size};  
      UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);  
      CGContextAddPath(UIGraphicsGetCurrentContext(),  
                       [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);  
      CGContextClip(UIGraphicsGetCurrentContext());  
      [self drawInRect:rect];  
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
      
      UIGraphicsEndImageContext();  
      
      return image;  
    }  
    //然后调用时就直接传一个圆角来处理:  
      
    imgView.image = [[UIImage imageNamed:@"test"] hyb_imageWithCornerRadius:4];  
    //最直接的方法就是使用如下属性设置:  
    imgView.layer.cornerRadius = 10;  
    // 这一行代码是很消耗性能的  
    imgView.clipsToBounds = YES;  
    //好处是使用简单,操作方便。坏处是离屏渲染(off-screen-rendering)需要消耗性能。对于图片比较多的视图上,不建议使用这种方法来设置圆角。通常来说,计算机系统中CPU、GPU、显示器是协同工作的。CPU计算好显示内容提交到GPU,GPU渲染完成后将渲染结果放入帧缓冲区。  
    //简单来说,离屏渲染,导致本该GPU干的活,结果交给了CPU来干,而CPU又不擅长GPU干的活,于是拖慢了UI层的FPS(数据帧率),并且离屏需要创建新的缓冲区和上下文切换,因此消耗较大的性能。
    
    • 删除缓存
    - (void)removeCache  
    {  
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];  
        NSLog(@"%@",cachePath);  
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];  
        for (NSString *p in files) {  
            NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath, p];  
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {  
                [[NSFileManager defaultManager] removeItemAtPath:path error:nil];  
            }  
        }  
    }  
    
    • 计算清除的缓存大小
    - (CGFloat)floatWithPath:(NSString *)path  
    {  
        CGFloat num = 0;  
        NSFileManager *man = [NSFileManager defaultManager];  
        if ([man fileExistsAtPath:path]) {  
            NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];  
            NSString *fileName;  
            while ((fileName = [childFile nextObject]) != nil) {  
                NSString *fileSub = [path stringByAppendingPathComponent:fileName];  
                num += [self fileSizeAtPath:fileSub];  
            }  
        }  
        return num / (1024.0 * 1024.0);  
    }  
    
    • 计算单个文件大小
    - (long long)fileSizeAtPath:(NSString *)file  
    {  
        NSFileManager *man = [NSFileManager defaultManager];  
        if ([man fileExistsAtPath:file]) {  
            return [[man attributesOfItemAtPath:file error:nil] fileSize];  
        }  
        return 0;  
    }  
    
    • 通过视图,寻找父控制器
    - (UIViewController *)viewController
    {
        for (UIView* next = [self superview]; next; next = next.superview) {
            UIResponder *nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                return (UIViewController *)nextResponder;
            }
        }
        return nil;
    }
    
    • 给textField加上右边的视图
      UIButton *eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
      [eyeBtn setImage:[UIImage imageNamed:@"icon_close_eye"] forState:UIControlStateNormal];
      [eyeBtn setImage:[UIImage imageNamed:@"icon_open_eye"] forState:UIControlStateSelected];
            eyeBtn.width = 30;
            eyeBtn.height = 30;
            _passwordField.rightView = eyeBtn;
            [eyeBtn addTarget:self action:@selector(showPwd:) forControlEvents:UIControlEventTouchUpInside];
            _passwordField.rightViewMode = UITextFieldViewModeAlways;
    
    • UITableViewCell选中后其子视图颜色会改变,重写下面两个方法可以避免UI出入
    - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
        [super setHighlighted:highlighted animated:animated];
        
        self.lineview.backgroundColor = MColor;
    }
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
        [super setSelected:selected animated:animated];
        
        self.lineview.backgroundColor = MColor;
    }
    
    • 传入一段H5代码获取其中所有的img元素的Url
    - (NSArray *) getImageurlFromHtml:(NSString *) webString
    {
        NSMutableArray * imageurlArray = [NSMutableArray arrayWithCapacity:1];
        
        //标签匹配
        NSString *parten = @"<img(.*?)>";
        NSError* error = NULL;
        NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:0 error:&error];
        
        NSArray* match = [reg matchesInString:webString options:0 range:NSMakeRange(0, [webString length] - 1)];
        
        for (NSTextCheckingResult * result in match) {
            
            //过去数组中的标签
            NSRange range = [result range];
            NSString * subString = [webString substringWithRange:range];
            
            
            //从图片中的标签中提取ImageURL
            NSRegularExpression *subReg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
            NSArray* match = [subReg matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
            NSTextCheckingResult * subRes = match[0];
            NSRange subRange = [subRes range];
            subRange.length = subRange.length -1;
            NSString * imagekUrl = [subString substringWithRange:subRange];
            
            //将提取出的图片URL添加到图片数组中
            [imageurlArray addObject:imagekUrl];
        }
        return imageurlArray;
    }
    
    • 给label加下划线,中划线
        NSString *textStr = [NSString stringWithFormat:@"¥%@", oldPrice];
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName:  [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic];
        self.oldPrice_label.attributedText = attribtStr;
    
    • 利用Quartz2D画一张图片保存到指定位置
       UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
       CGContextRef ctx = UIGraphicsGetCurrentContext();
       CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));
       CGContextStrokePath(ctx);
       UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
       NSData *data=UIImagePNGRepresentation(image);
       [data writeToFile:@"/Users/yy-info/Documents/Practice/imgName.png" atomically:YES];
    
    • 给UI控件加上虚线框(Quartz2D绘图)
        
        CGFloat width = _label.frame.size.width;
        
        CGFloat height = _label.frame.size.height;
        
        CAShapeLayer*shapelayer = [CAShapeLayer layer];
        
        shapelayer.bounds=CGRectMake(0,0, width, height);
        
        shapelayer.position=CGPointMake(CGRectGetMinX(_label.bounds),CGRectGetMinY(_label.bounds));
       
        shapelayer.anchorPoint = CGPointMake(0, 0);
        
        shapelayer.path= [UIBezierPath bezierPathWithRoundedRect:shapelayer.bounds cornerRadius:5].CGPath;
        
        shapelayer.lineWidth = 1;
        
        shapelayer.lineDashPattern=@[@5,@2];
        
        shapelayer.fillColor=nil;
        
        shapelayer.strokeColor= [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1].CGColor;
        
        [_label.layer addSublayer:shapelayer];
    

    *CALayer的震动

      CAKeyframeAnimation*kfa = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        CGFloat s =16;
        kfa.values=@[@(-s),@(0),@(s),@(0),@(-s),@(0),@(s),@(0)];
        //时长
        kfa.duration=.1f;
        //重复
        kfa.repeatCount=9;
        //移除
        kfa.removedOnCompletion=YES;
        [_label.layer addAnimation:kfa forKey:@"shake"];
    
    

    相关文章

      网友评论

          本文标题:iOS开发常用代码大全

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