整理一下用过的一点分类

自己用过,写过的一点分类,记录一下先。


图片发自简书App



NSdate

.h中:

// 是否为今天

- (BOOL)isToday;

//是否为昨天

- (BOOL)isYesterday;

//是否为今年

- (BOOL)isThisYear;

//返回一个只有年月日的时间

- (NSDate *)dateWithYMD;

// 获得与当前时间的差距

- (NSDateComponents *)deltaWithNow;

//获取今天周几

- (NSInteger)getNowWeekday;

//判断时间

+ (NSString *)readableDateWithDate:(NSString *)dateString;

- (NSDate *)hj_dateByAddingYears:(NSInteger)years; /// 从这个日期加上N年

- (NSDate *)hj_dateByAddingMonths:(NSInteger)months; /// 从这个日期加上N月

- (NSDate *)hj_dateByAddingWeeks:(NSInteger)weeks; /// 从这个日期加上N日

- (NSDate *)hj_dateByAddingDays:(NSInteger)days; /// 从这个日期加上N天

- (NSDate *)hj_dateByAddingHours:(NSInteger)hours; /// 从这个日期加上N小时

- (NSDate *)hj_dateByAddingMinutes:(NSInteger)minutes; /// 从这个日期加上N分钟

- (NSDate *)hj_dateByAddingSeconds:(NSInteger)seconds; /// 从这个日期加上N秒

.m中:

// 是否为今天

- (BOOL)isToday

{

NSCalendar *calendar = [NSCalendar currentCalendar];

int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear;

// 1.获得当前时间的年月日

NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];

// 2.获得self的年月日

NSDateComponents *selfCmps = [calendar components:unit fromDate:self];

return

(selfCmps.year == nowCmps.year) &&

(selfCmps.month == nowCmps.month) &&

(selfCmps.day == nowCmps.day);

}

// 是否为昨天

- (BOOL)isYesterday

{

// 2014-05-01

NSDate *nowDate = [[NSDate date] dateWithYMD];

// 2014-04-30

NSDate *selfDate = [self dateWithYMD];

// 获得nowDate和selfDate的差距

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];

return cmps.day == 1;

}

- (NSDate *)dateWithYMD

{

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];

fmt.dateFormat = @"yyyy-MM-dd";

NSString *selfStr = [fmt stringFromDate:self];

return [fmt dateFromString:selfStr];

}

//  是否为今年

- (BOOL)isThisYear

{

NSCalendar *calendar = [NSCalendar currentCalendar];

int unit = NSCalendarUnitYear;

// 1.获得当前时间的年月日

NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];

// 2.获得self的年月日

NSDateComponents *selfCmps = [calendar components:unit fromDate:self];

return nowCmps.year == selfCmps.year;

}

- (NSDateComponents *)deltaWithNow

{

NSCalendar *calendar = [NSCalendar currentCalendar];

int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];

}

+ (NSString *)readableDateWithDate:(NSString *)dateString {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *date = [dateFormatter dateFromString:dateString];

if (!date) {

return nil;

}

NSTimeInterval  timeInterval = [date timeIntervalSinceNow];

timeInterval = -timeInterval;

long temp = 0;

NSString *result;

if (timeInterval < 60) {

result = [NSString stringWithFormat:@"刚刚"];

} else if ((temp = timeInterval / 60) < 60) {

result = [NSString stringWithFormat:@"%ld分钟前", temp];

} else if((temp = temp / 60) < 24) {

result = [NSString stringWithFormat:@"%ld小时前",temp];

} else if ((temp = temp / 24) < 30) {

result = [NSString stringWithFormat:@"%ld天前",temp];

} else if((temp = temp / 30) < 12) {

result = [NSString stringWithFormat:@"%ld个月前",temp];

} else {

temp = temp / 12;

result = [NSString stringWithFormat:@"%ld年前",temp];

}

return  result;

}

//获取今天周几

- (NSInteger)getNowWeekday {

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *comps = [[NSDateComponents alloc] init];

NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |

NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDate *now = [NSDate date];

// 在真机上需要设置区域,才能正确获取本地日期,china:zh_CN

calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];

comps = [calendar components:unitFlags fromDate:now];

return [comps day];

}

//加一年

- (NSDate *)hj_dateByAddingYears:(NSInteger)years {

NSCalendar *calendar =  [NSCalendar currentCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setYear:years];

return [calendar dateByAddingComponents:components toDate:self options:0];

}

//加一月

- (NSDate *)hj_dateByAddingMonths:(NSInteger)months {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setMonth:months];

return [calendar dateByAddingComponents:components toDate:self options:0];

}

//加一周

- (NSDate *)hj_dateByAddingWeeks:(NSInteger)weeks {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setWeekOfYear:weeks];

return [calendar dateByAddingComponents:components toDate:self options:0];

}

//加一天

- (NSDate *)hj_dateByAddingDays:(NSInteger)days {

NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 86400 * days;

NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];

return newDate;

}

//加一小时

- (NSDate *)hj_dateByAddingHours:(NSInteger)hours {

NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 3600 * hours;

NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];

return newDate;

}

//加一分

- (NSDate *)hj_dateByAddingMinutes:(NSInteger)minutes {

NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 60 * minutes;

NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];

return newDate;

}

//加一秒

- (NSDate *)hj_dateByAddingSeconds:(NSInteger)seconds {

NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + seconds;

NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];

return newDate;

}

NSDictionary

.h中

- (void)property;

.m中

//根据字典生成模型属性代码,不用自己一个个敲

- (void)property

{

// 属性跟字典的key一一对应

NSMutableString *codes = [NSMutableString string];

// 遍历字典中所有key取出来

[self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

// key:属性名

NSString *code;

if ([obj isKindOfClass:[NSString class]]) {

code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSString *%@;",key];

}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){

code = [NSString stringWithFormat:@"@property (nonatomic ,assign) BOOL %@;",key];

}else if ([obj isKindOfClass:[NSNumber class]]){

code = [NSString stringWithFormat:@"@property (nonatomic ,assign) NSInteger %@;",key];

}else if ([obj isKindOfClass:[NSArray class]]){

code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSArray *%@;",key];

}else if ([obj isKindOfClass:[NSDictionary class]]){

code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSDictionary *%@;",key];

}

[codes appendFormat:@"\n%@\n",code];

}];

NSLog(@"%@",codes);

}

NSString

.h中

//有效的电话号码

- (BOOL) isValidMobileNumber;

//有效的真实姓名

- (BOOL) isValidRealName;

//是否只有中文

- (BOOL) isOnlyChinese;

//有效的银行卡号

- (BOOL) isValidBankCardNumber;

//有效的邮箱

- (BOOL) isValidEmail;

//检测有效身份证

//15位

- (BOOL) isValidIdentifyFifteen;

//18位

- (BOOL) isValidIdentifyEighteen;

//有效的验证码(根据自家的验证码位数进行修改)

- (BOOL) isValidVerifyCode;

.m中

//有效的电话号码

- (BOOL) isValidMobileNumber {

NSString* const MOBILE = @"^1(3|4|5|7|8)\\d{9}$";

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];

return [predicate evaluateWithObject:self];

}

//有效的真实姓名

- (BOOL) isValidRealName

{

NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{2,8}$";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];

return [predicate evaluateWithObject:self];

}

//是否只有中文

- (BOOL) isOnlyChinese

{

NSString * chineseTest=@"^[\u4e00-\u9fa5]{0,}$";

NSPredicate*chinesePredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",chineseTest];

return [chinesePredicate evaluateWithObject:self];

}

//有效的银行卡号

- (BOOL) isValidBankCardNumber {

NSString* const BANKCARD = @"^(\\d{16}|\\d{19})$";

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", BANKCARD];

return [predicate evaluateWithObject:self];

}

//有效的邮箱

- (BOOL) isValidEmail

{

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:self];

}

//检测有效身份证

//15位

- (BOOL) isValidIdentifyFifteen

{

NSString * identifyTest=@"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";

NSPredicate*identifyPredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",identifyTest];

return [identifyPredicate evaluateWithObject:self];

}

//18位

- (BOOL) isValidIdentifyEighteen

{

NSString * identifyTest=@"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";

NSPredicate*identifyPredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",identifyTest];

return [identifyPredicate evaluateWithObject:self];

}

//有效的验证码(根据自家的验证码位数进行修改)

- (BOOL) isValidVerifyCode

{

NSString *pattern = @"^[0-9]{4}";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

return [predicate evaluateWithObject:self];

}

UIBarButtonItem

.h中

//设置UIBarButtonItem图片

+(UIBarButtonItem *)barBtnItemWithImg:(NSString *)image highImg:(NSString *)highimage target:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

//设置UIBarButtonItem文字

+(UIBarButtonItem *)barBtnItemWithText:(NSString *)text textColor:(UIColor *)color target:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

.m中

//设置UIBarButtonItem图片

+(UIBarButtonItem *)barBtnItemWithImg:(NSString *)image highImg:(NSString *)highimage target:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

{

UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];

[btn setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];

[btn setBackgroundImage:[UIImage imageNamed:highimage] forState:UIControlStateHighlighted];

[btn sizeToFit];

[btn addTarget:target action:action forControlEvents:controlEvents];

return [[UIBarButtonItem alloc]initWithCustomView:btn];

}

//设置UIBarButtonItem文字

+(UIBarButtonItem *)barBtnItemWithText:(NSString *)text textColor:(UIColor *)color target:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

{

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

[btn addTarget:target action:action forControlEvents:controlEvents];

[btn setTitle:text forState:UIControlStateNormal];

[btn setTitleColor:color forState:UIControlStateNormal];

[btn sizeToFit];

[btn.titleLabel setFont:[UIFont systemFontOfSize:13.0] ];

return [[UIBarButtonItem alloc] initWithCustomView:btn];

}

UIColor

.h中

+ (UIColor *)colorFromHexRGB:(NSString *)colorString;

.m中

//设置颜色 ,如222222

+ (UIColor *)colorFromHexRGB:(NSString *)colorString

{

UIColor *result = nil;

unsigned int colorCode = 0;

unsigned char redByte, greenByte, blueByte;

if (nil != colorString)

{

NSScanner *scanner = [NSScanner scannerWithString:colorString];

(void) [scanner scanHexInt:&colorCode]; // ignore error

}

redByte = (unsigned char) (colorCode >> 16);

greenByte = (unsigned char) (colorCode >> 8);

blueByte = (unsigned char) (colorCode); // masks off high bits

result = [UIColor

colorWithRed: (float)redByte / 0xff

green: (float)greenByte/ 0xff

blue: (float)blueByte / 0xff

alpha:1.0];

return result;

}

宏:#define RGB(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]

UIImage

.h中

//图片渲染模式:始终绘制图片原始状态

+ (UIImage *)originalImageIgnoredRenderWithImageName:(NSString *)imageName;

//根据图片名返回拉伸倍数的图片

+(UIImage *)stretchableImageWithName:(NSString *)imageName capWidth:(CGFloat)Wfloat capHeight:(CGFloat)Hfloat;

/*

* 根据文字生成水印图片

* rect 是相对图片大小的位置

*/

+ (UIImage *)imageWithWaterMarkImage:(NSString *)imageName text:(NSString *)str textRect:(CGRect)rect;

// 根据颜色生成图片

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;

//通过Rect剪裁图片

- (UIImage *) imageByCropToRect:(CGRect)rect;

// 生成一个圆形图片

+ (UIImage *)circleImageNamed:(NSString *)imgName;

.m中

//图片渲染模式:始终绘制图片原始状态

+ (UIImage *)originalImageIgnoredRenderWithImageName:(NSString *)imageName

{

UIImage *image=[UIImage imageNamed:imageName];

return [image imageWithRenderingMode:1];

}

//根据图片名返回自由拉伸的图片

+(UIImage *)stretchableImageWithName:(NSString *)imageName capWidth:(CGFloat)Wfloat capHeight:(CGFloat)Hfloat

{

UIImage *image=[UIImage imageNamed:imageName];

return [image stretchableImageWithLeftCapWidth:image.size.width*Wfloat topCapHeight:image.size.height*Hfloat];

}

/*

* 根据文字生成水印图片

*/

+ (UIImage *)imageWithWaterMarkImage:(NSString *)imageName text:(NSString *)str textRect:(CGRect)rect;

{

UIImage *image = [UIImage imageNamed:imageName];

UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);

//把图片画上去

[image drawAtPoint:CGPointZero];

//绘制文字到图片

NSMutableDictionary *arrt = [NSMutableDictionary dictionary];

arrt[NSFontAttributeName] = [UIFont systemFontOfSize:20.0];

[str drawInRect:rect withAttributes:arrt];

// 从上下文获取图片

UIImage *imageWater = UIGraphicsGetImageFromCurrentImageContext();

//关闭上下文

UIGraphicsEndImageContext();

return imageWater;

}

/*

* 根据颜色生成图片

*/

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size

{

CGRect rect = CGRectMake(0, 0, size.width, size.height);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context,color.CGColor);

CGContextFillRect(context, rect);

UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return img;

}

//通过Rect剪裁图片

- (UIImage *)imageByCropToRect:(CGRect)rect {

rect.origin.x *= self.scale;

rect.origin.y *= self.scale;

rect.size.width *= self.scale;

rect.size.height *= self.scale;

if (rect.size.width <= 0 || rect.size.height <= 0) return nil;

CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);

UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];

CGImageRelease(imageRef);

return image;

}

// 生成一个圆形图片

+ (UIImage *)circleImageNamed:(NSString *)imgName

{

UIImage *image=[UIImage imageNamed:imgName];

UIGraphicsBeginImageContext(image.size);

// 上下文

CGContextRef context = UIGraphicsGetCurrentContext();

// 添加一个圆

CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);

CGContextAddEllipseInRect(context, rect);

// 裁剪

CGContextClip(context);

// 绘制图片到圆上面

[image drawInRect:rect];

// 获得图片

UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();

// 结束图形上下文

UIGraphicsEndImageContext();

return image1;

}

UILabel

.h中

+ (CGFloat)hj_getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;

+ (CGFloat)hj_getWidthWithTitle:(NSString *)title font:(UIFont *)font;

//中划线

+(NSAttributedString *)midLineWithString:(NSString *)text;

//下划线

+(NSAttributedString *)underLineWithString:(NSString *)text;

.m中

//根据文字,字体,label宽度 计算高度

+ (CGFloat)hj_getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font

{

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];

label.text = title;

label.font = font;

label.numberOfLines = 0;

[label sizeToFit];

CGFloat height = label.frame.size.height;

return height;

}

//计算宽度

+ (CGFloat)hj_getWidthWithTitle:(NSString *)title font:(UIFont *)font {

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];

label.text = title;

label.font = font;

[label sizeToFit];

return label.frame.size.width;

}

//中划线

+(NSAttributedString *)midLineWithString:(NSString *)text

{

NSDictionary *attriDic=@{NSStrikethroughStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle],NSStrikethroughColorAttributeName:[UIColor lightGrayColor]};

NSMutableAttributedString *attriStr=[[NSMutableAttributedString alloc]initWithString:text attributes:attriDic];

return attriStr;

}

//下划线

+(NSAttributedString *)underLineWithString:(NSString *)text

{

NSDictionary *attriDic=@{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle],NSStrikethroughColorAttributeName:[UIColor lightGrayColor]};

NSMutableAttributedString *attriStr=[[NSMutableAttributedString alloc]initWithString:text attributes:attriDic];

return attriStr;

}

UIView

.h中

@interface UIView (HJViewFrame)

@property (nonatomic,assign) CGFloat x;

@property (nonatomic,assign) CGFloat y;

@property (nonatomic,assign) CGFloat centerX;

@property (nonatomic,assign) CGFloat centerY;

@property (nonatomic,assign) CGFloat width;

@property (nonatomic,assign) CGFloat height;

@property (nonatomic,assign) CGSize size;

@property (nonatomic,assign) CGPoint origin;

@property (assign, nonatomic) CGFloat maxX;

@property (assign, nonatomic) CGFloat maxY;

-(void)setAddX:(CGFloat)addX;

-(void)setAddY:(CGFloat)addY;

/**

*  快速根据xib创建View

*/

+ (instancetype)hj_viewFromXib;

.m中

- (void)setX:(CGFloat)x

{

CGRect frame = self.frame;

frame.origin.x = x;

self.frame = frame;

}

- (void)setY:(CGFloat)y

{

CGRect frame = self.frame;

frame.origin.y = y;

self.frame = frame;

}

- (CGFloat)x

{

return self.frame.origin.x;

}

- (CGFloat)y

{

return self.frame.origin.y;

}

- (void)setWidth:(CGFloat)width

{

CGRect frame = self.frame;

frame.size.width = width;

self.frame = frame;

}

- (void)setHeight:(CGFloat)height

{

CGRect frame = self.frame;

frame.size.height = height;

self.frame = frame;

}

- (CGFloat)width

{

return self.frame.size.width;

}

- (CGFloat)height

{

return self.frame.size.height;

}

- (void)setSize:(CGSize)size

{

CGRect frame = self.frame;

frame.size = size;

self.frame = frame;

}

- (CGSize)size

{

return self.frame.size;

}

- (void)setOrigin:(CGPoint)origin

{

CGRect frame = self.frame;

frame.origin = origin;

self.frame = frame;

}

- (CGPoint)origin

{

return self.frame.origin;

}

- (void)setCenterX:(CGFloat)centerX

{

CGPoint center = self.center;

center.x = centerX;

self.center = center;

}

- (void)setCenterY:(CGFloat)centerY

{

CGPoint center = self.center;

center.y = centerY;

self.center = center;

}

- (CGFloat)centerX

{

return self.center.x;

}

- (CGFloat)centerY

{

return self.center.y;

}

- (void)setMaxX:(CGFloat)maxX{

CGRect frame = self.frame;

frame.origin.x = maxX - frame.size.width;

self.frame = frame;

}

- (CGFloat)maxX{

return CGRectGetMaxX(self.frame);

}

- (void)setMaxY:(CGFloat)maxY{

CGRect frame = self.frame;

frame.origin.y = maxY - frame.size.height;

self.frame = frame;

}

- (CGFloat)maxY{

return CGRectGetMaxY(self.frame);

}

-(void)setAddX:(CGFloat)addX

{

CGRect frame=self.frame;

frame.origin.x+=addX;

self.frame=frame;

}

-(void)setAddY:(CGFloat)addY

{

CGRect frame = self.frame;

frame.origin.y += addY;

self.frame = frame;

}

+ (instancetype)hj_viewFromXib

{

return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].firstObject;

}

推荐阅读更多精彩内容