自己封装的工具类一、NSString类型//手机号码验证+(BOOL)phoneText:(NSString*)string{ /** * 移动号段正则表达式 */ NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$"; /** * 联通号段正则表达式 */ NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$"; /** * 电信号段正则表达式 */ NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$"; NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM]; BOOL isMatch1 = [pred1 evaluateWithObject:string]; NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM]; BOOL isMatch2 = [pred2 evaluateWithObject:string]; NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM]; BOOL isMatch3 = [pred3 evaluateWithObject:string]; if (isMatch1 || isMatch2 || isMatch3) { return YES; }else{ return NO; }}//汉字转拼音+ (NSString *)transform:(NSString *)chinese{ NSMutableString *pinyin = [chinese mutableCopy]; CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); //去掉空格 NSString * contentping = [[pinyin lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""]; return contentping;}//时间计算 刚刚-几分钟前-几小时前+(NSString *)compareCurrentTime:(NSString*)str{ if (ios8orLater) { }else{ return @"版本过低"; } //创建时间对象 NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; //系统时间的字符串 NSDate * dateXT = [NSDate date]; NSCalendar * calendarXT = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *compXT = [calendarXT components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday fromDate:dateXT]; NSString * stringXT = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld:%ld",(long)compXT.year, (long)compXT.month, (long)compXT.day, (long)compXT.hour, (long)compXT.minute, (long)compXT.second]; //系统时间 NSDate *dateTimeXT = [formatter dateFromString:stringXT]; //发帖日期 NSDate *date0 = [formatter dateFromString:str]; //初始化日历 NSCalendar * calendar; if (ios8orLater) { calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; }else{ calendar = [NSCalendar autoupdatingCurrentCalendar]; } //拿到时间差(系统时间减去发帖时间) NSDateComponents *com = [calendar components:NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date0 toDate:dateTimeXT options:0]; //转化成秒 NSTimeInterval timeInterval =(long)com.day *86400 + (long)com.hour *3600+(long)com.minute * 60+(long)com.second; long temp = 0; NSString *result; //小于60 秒显示刚刚 if (timeInterval < 60) { result = [NSString stringWithFormat:@"刚刚"]; } //小于60分钟直接显示几分钟前 else if((temp = timeInterval/60) <60){ result = [NSString stringWithFormat:@"%ld分钟前",temp]; } //小于24小时直接显示几小时前 else if((temp = timeInterval/(60*60)) <24){ result = [NSString stringWithFormat:@"%ld小时前",temp]; } //小于7天显示几天前 else if((temp = timeInterval/(86400)) <7){ result = [NSString stringWithFormat:@"%ld天前",temp]; } //大于7天小于14天显示1周前 else if((temp = timeInterval/(86400*7)) <2){ result = [NSString stringWithFormat:@"%ld周前",temp]; } else{ //直接显示发帖日期 NSArray * arrayNew = [str componentsSeparatedByString:@"-"]; //切日 NSArray * arrayday = [[arrayNew lastObject] componentsSeparatedByString:@" "]; result =[NSString stringWithFormat:@"%@.%@.%@",[arrayNew firstObject],arrayNew[1],[arrayday firstObject]]; } return result;}//根据日期判断星座+(NSString *)getAstroWithMonth:(int)m day:(int)d{ NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯"; NSString *astroFormat = @"102123444543"; NSString *result; if (m<1||m>12||d<1||d>31){ return @"错误日期格式!"; } if(m==2 && d>29) { return @"错误日期格式!!"; }else if(m==4 || m==6 || m==9 || m==11) { if (d>30) { return @"错误日期格式!!!"; } } result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]]; return result;}#pragma mark ============== 秒杀时间 =====================+(NSString*)timeCha:(NSNumber*)start Endtime:(NSNumber*)endtime{ NSString * string; //开始时间 NSNumber * startDate = start; double sta = [startDate doubleValue]; //结束日期 NSNumber * endDate = endtime; double end = [endDate doubleValue]; //系统时间的毫秒 NSTimeInterval time=[[NSDate date] timeIntervalSince1970]*1000; double now = time; //NSTimeInterval返回的是double类型 //活动未开始 if (now < sta) { //得到还有多久开始的时间差时间差(秒) int cha = (now - sta)/1000; string = [NSString stringWithFormat:@"%d",cha]; } //活动进行中 if (now > sta && now < end) { //得到时间差(秒) int cha = (end - now)/1000; string = [NSString stringWithFormat:@"%d",cha]; } //活动已结束 if (now > end) { string = @"已结束"; } return string; }#pragma mark ============== 已知开始时间和结束时间的毫秒,计算开始、进行中、结束状态 =====================+(NSString*)timeStateStart:(double)sta Endtime:(double)end{ NSString * string; //系统时间的毫秒 NSTimeInterval time=[[NSDate date] timeIntervalSince1970]*1000; double now = time; //NSTimeInterval返回的是double类型 //活动未开始 if (now < sta) { string = @"未开始"; } //活动进行中 if (now > sta && now < end) { string = @"进行中"; } //活动已结束 if (now > end) { string = @"已结束"; } return string;}//通用正则匹配,可以匹配任意东西,只需要传入正则表达式跟字符串即可+ (NSString *)processWithString:(NSString *)string regularExpression:(NSString *)regularExpression { // 创建一个可变字符串,用来拼接符合条件的字符 NSMutableString *mString = [[NSMutableString alloc] init]; // 创建一个错误对象 NSError *error; // 正则 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression options:0 error:&error]; // 如果正则没有错误进行内部的代码 if (!error) { // 将符合条件的字符位置记录到数组中 NSArray *array = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)]; // 利用数组中的位置将所有符合条件的字符拼接起来 for (NSTextCheckingResult *result in array) { NSRange range = [result range]; NSString *mStr = [string substringWithRange:range]; [mString appendString:mStr]; } return mString; } else { NSLog(@"error is %@", error); } return nil;}//传入文本内容、字体大小、控件宽度返回计算的文本占用位置的大小(含宽,高)+(CGSize)sizeMyStrWith:(NSString*)text andFontSize:(CGFloat)fontsize andMineWidth:(CGFloat)Width{ //ios7 CGSize size = [text boundingRectWithSize:CGSizeMake(Width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]} context:nil].size; return size; }//毫秒转日期+(NSString * )dateChange:(NSNumber * )dateNum andFormat:(NSString*)formatStr{ //格式为 yyyy-MM-dd HH:mm:ss //毫秒转日期 NSString * stareStr = [NSString stringWithFormat:@"%@",dateNum]; double time= [stareStr doubleValue]; NSDate * d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //日期样式 dateFormatter.dateFormat = formatStr; [dateFormatter stringFromDate:d]; //日期 NSString * newTime=[NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:d]]; return newTime;}//日期转毫秒+(NSString* )dateHMChange:(NSString*)dateString andFormat:(NSString*)format{ //日期转毫秒(已经没有8个小时的时差了)// 格式:yyyy-MM-dd HH:mm:ss NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = format; NSDate * Minedate = [formatter dateFromString:dateString]; NSTimeInterval timeStamp= [Minedate timeIntervalSince1970]*1000; //NSTimeInterval返回的是double类型 double dateMs = timeStamp;// NSLog(@"日期转换的毫秒数为:%.f", dateMs); return [NSString stringWithFormat:@"%.f",dateMs];}//字符串或者NSNumber判空方法(可传入字符串类型和NSNumber类型)+(BOOL)isNULL:(id)stringOrNumber { if ([stringOrNumber isKindOfClass:[NSNull class]]) { return YES; } if (stringOrNumber == nil || stringOrNumber == NULL) { return YES; } if ([stringOrNumber isEqual:[NSNull null]]) { return YES; } if ([stringOrNumber isEqual:@"(null)"]) { return YES; } if ([stringOrNumber isEqual:@""]) {
return YES;
}
if ([stringOrNumber isEqual:@""]) {
return YES;
}
if (!stringOrNumber) {
return YES;
}
//字符串才能判长度
if ([stringOrNumber isKindOfClass:[NSString class]]) {
NSString * stringGet = stringOrNumber;
if (stringGet.length==0) {
return YES;
}
//字符串专有判法
if ([[stringGet stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
return YES;
}
}
return NO;
}
#pragma mark 同一个label中间几个字 变颜色、大小都能改变
//UILabel中的内容的部分字体颜色更改
//用法:self.integralLabel.attributedText =[NSString getLabelChangeColor:[UIColor orangeColor] andFont:[UIFont systemFontOfSize:22] andString1:@"我的" andChangeString:@"大的" andGetstring3:@"自己"];
+(NSMutableAttributedString*)getLabelChangeColor:(UIColor*)color andFont:(UIFont*)fout andString1:(NSString*)string1 andChangeString:(NSString*)string2 andGetstring3:(NSString*)string3{
//string2 是变色的部分
NSString *inteStr = [NSString stringWithFormat:@"%@%@%@",string1,string2,string3];
NSMutableAttributedString *inteMutStr = [[NSMutableAttributedString alloc] initWithString:inteStr];
//设置中间变红的字体大小颜色
NSRange orangeRange = NSMakeRange([[inteMutStr string] rangeOfString:string2].location, [[inteMutStr string] rangeOfString:string2].length);
[inteMutStr addAttributes:@{NSFontAttributeName:fout,NSForegroundColorAttributeName:color} range:orangeRange];
return inteMutStr;
}