UtilClass.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UtilClass : NSObject
#pragma 检测手机号
+ (BOOL)checkMoble:(NSString *)mobleNum;
#pragma 改变图片到指定大小
+ (UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size;
#pragma 数字校验
+ (BOOL)isPureNumber:(NSString *)string;
+ (BOOL)isPureFloat:(NSString*)string;
+ (BOOL)isPureInt:(NSString*)string;
#pragma 根据日期获取星期/月份
+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate;
+ (NSString*)monthStringFromDate:(NSDate*)inputDate;
#pragma 日期格式化(默认格式:yyyy年MM月dd日 HH:mm:ss)
+ (NSString *)dateToString:(NSDate *)date format:(NSString *)format;
#pragma 日期加减天数
+ (NSDate *)dateNextDay:(NSDate *)date andDays:(int)days;
#pragma 时间比较
+ (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay;
#pragma NSDate转时间戳
+ (NSString *)dateToTimeStamp:(NSDate *)date;
#pragma 字符串替换
+(NSString *)stringByReplacingCharacters:(NSString *)str from:(NSString *)fromStr to:(NSString *)toStr;
#pragma 根据身份证获取信息
+ (BOOL) IsIdentityCard:(NSString *)IDCardNumber;//验证
+ (NSString *)getIdentityCardSex:(NSString *)numberStr;//性别
+ (NSString *)getIdentityCardAge:(NSString *)numberStr;//年龄
+ (NSDate *)getIdentityCardBirthday:(NSString *)numberStr;//生日
#pragma 从颜色池获取随机颜色
+ (UIColor *)getColor:(int)num;
#pragma 获取文字宽度
+ (float) widthForString:(NSString *)value font:(UIFont *)font;
+ (float) heightForString:(NSString *)value font:(UIFont *)font width:(CGFloat)width;
#pragma 计算年龄
+ (NSInteger)ageWithDateOfBirth:(NSDate *)date;
#pragma 颜色转uiimage
+ (UIImage*) createImageWithColor: (UIColor*) color;
#pragma uilabel 部分字体颜色修改
+ (NSMutableAttributedString *)getAttrStr:(NSString *)str subStr:(NSString *)subStr setColor:(UIColor *)color setFont:(UIFont *)font;
#pragma json转Dic
+ (NSDictionary *)jsonStrToDictionary:(NSString *)jsonStr;
#pragma 获取ip地址
+ (NSString *)getIPAddresses;
#pragma 获取view的controller
+ (UIViewController *)findViewController:(UIView *)sourceView;
#pragma uiview转uiimage
+ (UIImage*)convertViewToImage:(UIView*)v;
@end
UtilClass.m
#import "UtilClass.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
@implementation UtilClass
#pragma mark 检测手机号
+ (BOOL)checkMoble:(NSString *)mobleNum{
NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
return [regextestmobile evaluateWithObject:mobleNum];
}
#pragma 改变图片到指定大小
+ (UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
UIGraphicsBeginImageContext(size); //size 为CGSize类型,即你所需要的图片尺寸
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage; //返回的就是已经改变的图片
}
#pragma mark 数字校验
//判断是否为整形:
+ (BOOL)isPureInt:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为浮点形:
+ (BOOL)isPureFloat:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return[scan scanFloat:&val] && [scan isAtEnd];
}
//判断是否是数字
+ (BOOL)isPureNumber:(NSString *)string{
if([self isPureInt:string] || [self isPureFloat:string])
return YES;
else
return NO;
}
//根据日期获取星期
+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"日", @"一", @"二", @"三", @"四", @"五", @"六", nil];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
[calendar setTimeZone: timeZone];
NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
return [weekdays objectAtIndex:theComponents.weekday];
}
+ (NSString*)monthStringFromDate:(NSDate*)inputDate {
NSArray *month = [NSArray arrayWithObjects: [NSNull null], @"一月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月", @"九月", @"十月", @"十一月", @"十二月", nil];
;
return [month objectAtIndex:[[self dateToString:inputDate format:@"MM"] integerValue]];
}
//日期格式化
+ (NSString *)dateToString:(NSDate *)date format:(NSString *)format{
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
if(format){
[formatter setDateFormat:format];
}else{
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
}
return [formatter stringFromDate:date];
}
//日期加减几天
+ (NSDate *)dateNextDay:(NSDate *)date andDays:(int)days{
return [NSDate dateWithTimeInterval:24*60*60*days sinceDate:date];
}
//时间比较
+ (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
if (result == NSOrderedDescending) {
//NSLog(@"Date1 is in the future");
return 1;
}
else if (result == NSOrderedAscending){
//NSLog(@"Date1 is in the past");
return -1;
}
//NSLog(@"Both dates are the same");
return 0;
}
//NSDate转时间戳
+ (NSString *)dateToTimeStamp:(NSDate *)date{
return [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]*1000];
}
//字符串替换
+ (NSString *)stringByReplacingCharacters:(NSString *)str from:(NSString *)fromStr to:(NSString *)toStr{
NSRange rang = [str rangeOfString:fromStr];
if(rang.length != 0){
str = [str stringByReplacingCharactersInRange:rang withString:toStr];
}
return str;
}
//身份证校验
+ (BOOL) IsIdentityCard:(NSString *)IDCardNumber
{
if (IDCardNumber.length <= 0) {
return NO;
}
NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
return [identityCardPredicate evaluateWithObject:IDCardNumber];
}
/**
从身份证上获取年龄 18位身份证
*/
+ (NSString *)getIdentityCardAge:(NSString *)numberStr
{
NSDateFormatter *formatterTow = [[NSDateFormatter alloc]init];
[formatterTow setDateFormat:@"yyyy-MM-dd"];
NSDate *bsyDate = [formatterTow dateFromString:[self birthdayStrFromIdentityCard:numberStr]];
NSTimeInterval dateDiff = [bsyDate timeIntervalSinceNow];
int age = trunc(dateDiff/(60*60*24))/365;
return [NSString stringWithFormat:@"%d",-age];
}
+ (NSDate *)getIdentityCardBirthday:(NSString *)numberStr{
NSDateFormatter *formatterTow = [[NSDateFormatter alloc]init];
[formatterTow setDateFormat:@"yyyy-MM-dd"];
return [formatterTow dateFromString:[self birthdayStrFromIdentityCard:numberStr]];
}
+ (NSString *)birthdayStrFromIdentityCard:(NSString *)numberStr
{
NSMutableString *result = [NSMutableString stringWithCapacity:0];
NSString *year = nil;
NSString *month = nil;
BOOL isAllNumber = YES;
NSString *day = nil;
if([numberStr length]<18)
return result;
//**从第6位开始 截取8个数
NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(6, 8)];
//**检测前12位否全都是数字;
const char *str = [fontNumer UTF8String];
const char *p = str;
while (*p!='\0') {
if(!(*p>='0'&&*p<='9'))
isAllNumber = NO;
p++;
}
if(!isAllNumber)
return result;
year = [NSString stringWithFormat:@"19%@",[numberStr substringWithRange:NSMakeRange(8, 2)]];
// NSLog(@"year ==%@",year);
month = [numberStr substringWithRange:NSMakeRange(10, 2)];
// NSLog(@"month ==%@",month);
day = [numberStr substringWithRange:NSMakeRange(12,2)];
// NSLog(@"day==%@",day);
[result appendString:year];
[result appendString:@"-"];
[result appendString:month];
[result appendString:@"-"];
[result appendString:day];
// NSLog(@"result===%@",result);
return result;
}
/**
* 从身份证上获取性别
*/
+ (NSString *)getIdentityCardSex:(NSString *)numberStr
{
NSString *sex = @"";
//获取18位 二代身份证 性别
if (numberStr.length==18)
{
int sexInt=[[numberStr substringWithRange:NSMakeRange(16,1)] intValue];
if(sexInt%2!=0)
{
NSLog(@"1");
sex = @"1";
}
else
{
NSLog(@"2");
sex = @"2";
}
}
// 获取15位 一代身份证 性别
if (numberStr.length==15)
{
int sexInt=[[numberStr substringWithRange:NSMakeRange(14,1)] intValue];
if(sexInt%2!=0)
{
NSLog(@"1");
sex = @"1";
}
else
{
NSLog(@"2");
sex = @"2";
}
}
return sex;
}
//颜色池
+ (UIColor *)getColor:(int)num{
NSArray<UIColor *> *a = [[NSArray alloc]initWithObjects:[UIColor colorWithRed:207/255.0 green:248/255.0 blue:246/255.0 alpha:1.0],
[UIColor colorWithRed:148/255.0 green:212/255.0 blue:212/255.0 alpha:1.0],
[UIColor colorWithRed:136/255.0 green:180/255.0 blue:187/255.0 alpha:1.0],
[UIColor colorWithRed:118/255.0 green:174/255.0 blue:175/255.0 alpha:1.0],
[UIColor colorWithRed:42/255.0 green:109/255.0 blue:130/255.0 alpha:1.0], nil];
NSArray<UIColor *> *b = [[NSArray alloc]initWithObjects:[UIColor colorWithRed:271/255.0 green:80/255.0 blue:138/255.0 alpha:1.0],
[UIColor colorWithRed:254/255.0 green:149/255.0 blue:7/255.0 alpha:1.0],
[UIColor colorWithRed:254/255.0 green:247/255.0 blue:120/255.0 alpha:1.0],
[UIColor colorWithRed:106/255.0 green:167/255.0 blue:134/255.0 alpha:1.0],
[UIColor colorWithRed:53/255.0 green:194/255.0 blue:209/255.0 alpha:1.0], nil];
NSArray<UIColor *> *c = [[NSArray alloc]initWithObjects:[UIColor colorWithRed:64/255.0 green:89/255.0 blue:128/255.0 alpha:1.0],
[UIColor colorWithRed:149/255.0 green:165/255.0 blue:124/255.0 alpha:1.0],
[UIColor colorWithRed:217/255.0 green:184/255.0 blue:162/255.0 alpha:1.0],
[UIColor colorWithRed:191/255.0 green:134/255.0 blue:134/255.0 alpha:1.0],
[UIColor colorWithRed:179/255.0 green:48/255.0 blue:80/255.0 alpha:1.0], nil];
NSArray<UIColor *> *d = [[NSArray alloc]initWithObjects:[UIColor colorWithRed:193/255.0 green:37/255.0 blue:82/255.0 alpha:1.0],
[UIColor colorWithRed:255/255.0 green:102/255.0 blue:0/255.0 alpha:1.0],
[UIColor colorWithRed:245/255.0 green:199/255.0 blue:0/255.0 alpha:1.0],
[UIColor colorWithRed:106/255.0 green:150/255.0 blue:31/255.0 alpha:1.0],
[UIColor colorWithRed:179/255.0 green:100/255.0 blue:53/255.0 alpha:1.0], nil];
NSArray<UIColor *> *e = [[NSArray alloc]initWithObjects:[UIColor colorWithRed:192/255.0 green:255/255.0 blue:140/255.0 alpha:1.0],
[UIColor colorWithRed:255/255.0 green:247/255.0 blue:140/255.0 alpha:1.0],
[UIColor colorWithRed:255/255.0 green:208/255.0 blue:140/255.0 alpha:1.0],
[UIColor colorWithRed:140/255.0 green:234/255.0 blue:255/255.0 alpha:1.0],
[UIColor colorWithRed:255/255.0 green:140/255.0 blue:257/255.0 alpha:1.0], nil];
if(num < 0){
num = arc4random() % 5;
}
if(num > 4){
num = num % 5;
}
NSArray<UIColor *> *returnArray;
switch (num) {
case 0:
returnArray = a;
break;
case 1:
returnArray = b;
break;
case 2:
returnArray = c;
break;
case 3:
returnArray = d;
break;
case 4:
returnArray = e;
break;
default:
break;
}
int x = arc4random() % 5;
UIColor *returnColor = [UIColor whiteColor];
if(returnArray){
return returnArray[x];
}else{
return returnColor;
}
}
+(float) widthForString:(NSString *)value font:(UIFont *)font
{
NSDictionary *dict=@{NSFontAttributeName:font};
CGRect rect = [value boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:dict context:nil];
return rect.size.width;
}
+(float) heightForString:(NSString *)value font:(UIFont *)font width:(CGFloat)width
{
NSDictionary *dict=@{NSFontAttributeName:font};
CGRect rect = [value boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:dict context:nil];
return rect.size.height;
}
+ (NSInteger)ageWithDateOfBirth:(NSDate *)date
{
// 出生日期转换 年月日
NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSInteger brithDateYear = [components1 year];
NSInteger brithDateDay = [components1 day];
NSInteger brithDateMonth = [components1 month];
// 获取系统当前 年月日
NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger currentDateYear = [components2 year];
NSInteger currentDateDay = [components2 day];
NSInteger currentDateMonth = [components2 month];
// 计算年龄
NSInteger iAge = currentDateYear - brithDateYear - 1;
if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) {
iAge++;
}
return iAge;
}
+ (UIImage*) createImageWithColor: (UIColor*) color
{
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
+ (NSMutableAttributedString *)getAttrStr:(NSString *)str subStr:(NSString *)subStr setColor:(UIColor *)color setFont:(UIFont *)font
{
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
if(subStr.length <= 0)
return attrStr;
NSRange range = [str rangeOfString:subStr];
if(color)
[attrStr addAttribute:NSForegroundColorAttributeName value:color range:range]; //设置字体颜色
if(font)
[attrStr addAttribute:NSFontAttributeName value:font range:range];
return attrStr;
}
+ (NSDictionary *)jsonStrToDictionary:(NSString *)jsonStr
{
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
NSData *jsonData= [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableLeaves
error:&error];
if (jsonObject != nil && error == nil) {
return jsonObject;
} else {
// 解析错误
return nil;
}
}
+ (NSString *)getIPAddresses {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
+ (UIViewController *)findViewController:(UIView *)sourceView
{
id target=sourceView;
while (target) {
target = ((UIResponder *)target).nextResponder;
if ([target isKindOfClass:[UIViewController class]]) {
break;
}
}
return target;
}
+ (UIImage*)convertViewToImage:(UIView*)v{
CGSize s = v.bounds.size;
// 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end