iOS-常用小功能汇集

1、 url编码

+ (NSString *)urlEncodeString:(NSString *)urlString{
    NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return encodedString;
}

2、 从故事板获取视图控制器

+ (id)ViewControllerFromStoryBoard:(NSString *)name WithIdentifier:(NSString *)identifier{
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:name bundle:[NSBundle mainBundle]];
    return [storyBoard instantiateViewControllerWithIdentifier:identifier];
}

3、 判断是否是空字符串

+ (BOOL)isEmptyString:(NSString *)string{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([string isKindOfClass:[NSString class]]){
        if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0){
            return YES;
        }
    }
    return NO;
}

4、 判断是否包含字符串(兼容iOS7)

+ (BOOL)sourceStr:(NSString *)source containsStr:(NSString *)contains{
    BOOL isContained = NO;
    if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 8.0 ? YES : NO)) {
        NSRange range = [source rangeOfString:contains];
        if(range.length > 0){
            isContained = YES;
        }
    }
    else{
        isContained = [source containsString:contains];
    }
    return isContained;
}

5、 对图片尺寸进行压缩

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

6、 验证手机号

+ (BOOL)isMobile:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动:China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通:China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信:China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";


    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];

    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

7、 匹配用户密码6-16位数字和字母组合

+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;   
}

8、 验证邮箱

+ (BOOL) validateEmail:(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];
}

9、 字典转字符串

+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];  
}

10、 数组转字符串

+ (NSString*)arrryToJson:(NSArray *)arr
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
}

11、 判断字符串是否为纯数字

+(BOOL)isPureNumandCharacters:(NSString *)string
 {
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

12、适配文字高度
①系统默认行间距

+ (CGFloat)stringHeight:(NSString *)str width:(CGFloat)width font:(int)font{
    float height=[str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size.height;
    return height;
}

②自定义行间距

+ (CGFloat)stringHeight:(NSString *)str width:(CGFloat)width font:(int)font space:(float)space{
    NSMutableParagraphStyle*paragraph =[[NSMutableParagraphStyle alloc]init];
    paragraph.alignment=NSTextAlignmentJustified;
    paragraph.firstLineHeadIndent=0;
    paragraph.paragraphSpacingBefore=0;
    paragraph.lineSpacing=space;
    paragraph.hyphenationFactor=1.0;
    float height=[str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font],NSParagraphStyleAttributeName:paragraph} context:nil].size.height;
    return height;
}

13、 适配文字宽度

+ (CGFloat)stringWidth:(NSString *)str higth:(CGFloat)higth font:(int)font{
    float width=[str boundingRectWithSize:CGSizeMake(MAXFLOAT, higth) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size.height;
    return width;
}

14、 为控件上、下、左、右选择性画线

-(void)addLineToSomeThing:(id)anyThing isTop:(BOOL)isTop isBottom:(BOOL)isBottom isLeft:(BOOL)isLeft isRight:(BOOL)isRight{
    if ([anyThing isKindOfClass:[UIView class]]){
        UIView *anyView=(UIView *)anyThing;
        float height=anyView.frame.size.height;
        float width=anyView.frame.size.width;
        if (isTop) {
            CALayer *topBorder = [CALayer layer];
            topBorder.frame = CGRectMake(0.0f, 0.0f, width, 1.0f);
            topBorder.backgroundColor = [UIColor blackColor].CGColor;
            [anyView.layer addSublayer:topBorder];
        }
        if (isBottom) {
            CALayer *bottomBorder = [CALayer layer];
            bottomBorder.frame = CGRectMake(0.0f, height-1.0, width, 1.0f);
            bottomBorder.backgroundColor = [UIColor blackColor].CGColor;
            [anyView.layer addSublayer:bottomBorder];
        }
        if (isLeft) {
            CALayer *leftBorder = [CALayer layer];
            leftBorder.frame = CGRectMake(0.0f, 0.0f, 1.0f, height);
            leftBorder.backgroundColor = [UIColor blackColor].CGColor;
            [anyView.layer addSublayer:leftBorder];
        }
        if (isRight) {
            CALayer *rightBorder = [CALayer layer];
            rightBorder.frame = CGRectMake(width-1, 0.0f, 1.0f, height);
            rightBorder.backgroundColor = [UIColor blackColor].CGColor;
            [anyView.layer addSublayer:rightBorder];
        }
    }  
}

15、验证有1位小数的数字

+(BOOL)validateNumberHasPoint:(NSString *)textString{
    NSString *regex = @"^[0-9]+(.[0-9]{1})?$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [numberPre evaluateWithObject:textString]; 
}

验证有2位小数的数字(同理可自行修改)

+(BOOL)validateNumberHasPoint:(NSString *)textString{
      NSString *regex = @"^[0-9]+(.[0-9]{1,2})?$";
      NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
      return [numberPre evaluateWithObject:textString]; 
 }

16、改变文本行间距

+ (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space {
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
    [label sizeToFit];  
}

你可能感兴趣的:(iOS-常用小功能汇集)