《IOS开发笔记》iOS学霸笔记iOS笔记

iOS 常用正则,时间戳和日期转换,字符串宽高行数获取,高效切圆

2017-09-14  本文已影响35人  一颗小花菜

常用的公共方法类,有需要的可随时查看使用

#import <Foundation/Foundation.h>
@interface PublicMethod : NSObject
/**
 * 计算指定时间与当前的时间差
 * @param compareStr   某一指定时间戳
 * @return 多少(秒or分or天or月or年)+前 (比如,3天前、10分钟前)
 */
+(NSString *)compareCurrentTime:(NSString*)compareStr;
/**
 * 获取当前时间戳
 */
+(NSString *)getNowTimeTimestamp;
/**
 * 获取当前时间:年月日
 */
+(NSString*)getNowTime;
/**
 * 获取某个时间的时间戳
 */
+(double)getTheretime:(NSString *)time;
/*
 *
 转换秒数为分钟时长
 */
+(NSString *)getTime:(NSInteger)second;
/*
 *
 字符串非空判断
 */
+ (BOOL)isnull_string:(NSString *)str;
/*
 *
 时间戳转化为时间-月-日-时-分
 */
+ (NSString *)timeWithTimeIntervalString:(NSString *)timeString;
/*
 *
 时间戳转化为时间-时-分
 */
+ (NSString *)timeWithTime:(NSString *)timeString;
/*
 获取当前时间的前几天/后几天
 */
+(NSString*)nextDay:(NSInteger)day  isday:(BOOL)isday  style:    (NSString*)style;
/*
 *
 手机号正则
 */
+(BOOL)isMobileNumber:(NSString *)mobileNum;
/*
 *
 密码正则(6-15 字母+数字)
 */
+(BOOL)judgePassWordLegal:(NSString *)pass;
/**
 判断字符串是否包含emoji表情
 */
+ (BOOL)stringContainsEmoji:(NSString *)string;
/*
 *
 一个lable两种字号两种颜色(都不相同)
 */
+ (NSAttributedString *)attributeText:(NSString *)leadString color:(UIColor *)leadColor appendString:(NSString *)appendString appendColor:(UIColor *)appendColor attributeFont1:(UIFont *)attributeFont1 attributeFont2:(UIFont *)attributeFont2 lineSpacing:(NSUInteger)lineSpacing;
/*
 * 
 获取字符宽度
 */
+(float)widhForString:(NSString*)value fountSize:(float)fountsize;
/*
 *
 获取字符高度
 */
+(float)heightForString:(NSString*)value fountSize:(float)fountsize;
/*
 *
 获取一段文字行数
 */
+(CGFloat)getLineNum:(NSString*)str  font:(UIFont*)font labelWidth:(CGFloat)width;


/**
 切圆角
 @param view 视图
 */
+ (void)cutRoundView:(UIView *)view;
.m
#import "PublicMethod.h"

@implementation PublicMethod
/**
 * 计算指定时间与当前的时间差
 * @param compareStr   某一指定时间戳
 * @return 多少(秒or分or天or月or年)+前 (比如,3天前、10分钟前)
 */
+(NSString *)compareCurrentTime:(NSString*)compareStr{

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:[compareStr intValue]];
NSString* dateString = [dateFormatter stringFromDate:timeDate];
//八小时时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:timeDate];
NSDate *mydate = [timeDate dateByAddingTimeInterval:interval];
NSDate *nowDate = [[NSDate date]dateByAddingTimeInterval:interval];
//两个时间间隔
NSTimeInterval timeInterval = [mydate timeIntervalSinceDate:nowDate];
timeInterval = -timeInterval;
long temp = 0;
//    NSString *time;
if (timeInterval<60) {
    return  [NSString stringWithFormat:@"刚刚"];
}else if ((temp = timeInterval/60)<60){
    return [NSString stringWithFormat:@"%ld分钟前",temp];
}else if ((temp = timeInterval/(60*60))<24){
    return [NSString stringWithFormat:@"%ld小时前",temp];
}else if((temp = timeInterval/(24*60*60))<30){
    return dateString;
}else if (((temp = timeInterval/(24*60*60*30)))<12){
    return dateString;
}else {
    temp = timeInterval/(24*60*60*30*12);
    return dateString;
}
}
/**
 * 获取当前时间戳
 */
+(NSString *)getNowTimeTimestamp{

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

[formatter setDateStyle:NSDateFormatterMediumStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

//设置时区,这个对于时间的处理有时很重要

NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

[formatter setTimeZone:timeZone];

NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];

return timeSp;
}
//获取当前时间:年-月-日
+(NSString*)getNowTime{
NSDate *date = [NSDate date];

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

[formatter setDateStyle:NSDateFormatterMediumStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

[formatter setDateFormat:@"YYYYMMdd"];
NSString *DateTime = [formatter stringFromDate:date];

return DateTime;
}
//获取某个时间段的时间戳
+(double)getTheretime:(NSString *)time{
//    获取当天6:00后的时间
NSDate *contractTimeDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd"];
NSString *sixDate = [formatter stringFromDate:contractTimeDate];
sixDate = [NSString stringWithFormat:@"%@%@", sixDate, time];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
NSDate *sixDate2 = [formatter dateFromString:sixDate];

NSTimeInterval sixInterval = [sixDate2 timeIntervalSince1970];//今日06:00点的时间戳

return sixInterval ;
}
//***  获取当前时间的前几天/后几天
+(NSString*)nextDay:(NSInteger)day  isday:(BOOL)isday  style:(NSString*)style{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSInteger dis = day; //前后的天数
NSDate*nowDate = [NSDate date];
[dateFormatter setDateFormat:style];
NSDate* theDate;
if(dis!=0)
{
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    //后一天
    if (isday==YES) {
        theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*dis ];
    }
    //前一天
    else
    {
        theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*dis ];
    }
}
else
{
    theDate = nowDate;
}
return [dateFormatter stringFromDate:theDate];
}


#pragma mark - 转换秒数时长
+ (NSString *)getTime:(NSInteger)second{
NSString *time;
if (second < 60) {
    time = [NSString stringWithFormat:@"00:00:%02ld",(long)second];
}
else {
    if (second < 3600) {
        time = [NSString stringWithFormat:@"00:%02ld:%02ld",second/60,second%60];
    }
    else {
        time = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",second/3600,(second-second/3600*3600)/60,second%60];
    }
}
return time;
}

/**
 *  判断字符串是否为空
 *  @param str 要判断的字符串
 *  @return 是否为空 yes:不为空
 */
+ (BOOL)isnull_string:(NSString *)str{
if (str != nil && ![str isKindOfClass:[NSNull class]] && ![[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]){
    return YES;
}
return NO;
}


/**
 时间戳转化为时间-月-日-时-分
 */
+ (NSString *)timeWithTimeIntervalString:(NSString *)timeString{
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm"];

NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[timeString integerValue]];

NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];

return confromTimespStr;
}
/**
 时间戳转化为时间-时-分
 */
+ (NSString *)timeWithTime:(NSString *)timeString{
// 格式化时间
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"HH:mm"];
NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
NSString* dateString = [formatter stringFromDate:date];
return dateString;
}
#pragma mark - 手机号码正则
+(BOOL)isMobileNumber:(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;
}
}
#pragma  mark - 密码正则
+(BOOL)judgePassWordLegal:(NSString *)pass{
BOOL result = false;
if ([pass length] >= 7){
    // 判断长度大于7位后再接着判断是否同时包含数字和字符
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{7,12}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    result = [pred evaluateWithObject:pass];
}
return result;
}

#pragma mark -- 判断emoji表情
+ (BOOL)stringContainsEmoji:(NSString *)string{

__block BOOL returnValue = NO;

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByComposedCharacterSequences
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                            const unichar high = [substring characterAtIndex: 0];
                            
                            // Surrogate pair (U+1D000-1F9FF)
                            if (0xD800 <= high && high <= 0xDBFF) {
                                const unichar low = [substring characterAtIndex: 1];
                                const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                                
                                if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
                                    returnValue = YES;
                                }
                                
                                // Not surrogate pair (U+2100-27BF)
                            } else {
                                if (0x2100 <= high && high <= 0x27BF){
                                    returnValue = YES;
                                }
                            }
                        }];

return returnValue;
}

//** 一个Lable设置两种字体颜色和大小
+ (NSAttributedString *)attributeText:(NSString *)leadString color:(UIColor *)leadColor appendString:(NSString *)appendString appendColor:(UIColor *)appendColor attributeFont1:(UIFont *)attributeFont1 attributeFont2:(UIFont *)attributeFont2 lineSpacing:(NSUInteger)lineSpacing{
if (!leadString || !appendString) {
    return [[NSMutableAttributedString alloc] init];
}

if (![self isnull_string:leadString] && [self isnull_string:appendString]) {
    NSDictionary *attributeAppendColor = @{NSForegroundColorAttributeName:appendColor,NSFontAttributeName:attributeFont2};


    NSMutableAttributedString *attributeAppendString = [[NSMutableAttributedString alloc]
                                                 initWithString:appendString
                                                 attributes:attributeAppendColor];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing; // 调整行间距
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    NSRange range = NSMakeRange(0, [attributeAppendString length]);
    [attributeAppendString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];

    return attributeAppendString;

}else if (![self isnull_string:appendString] && [self isnull_string:leadString]) {
    NSDictionary *attributeLeadColor = @{NSForegroundColorAttributeName:leadColor,NSFontAttributeName:attributeFont1};

    NSMutableAttributedString *attributeLeadString = [[NSMutableAttributedString alloc]
                                                      initWithString:leadString
                                                      attributes:attributeLeadColor];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing; // 调整行间距
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    NSRange range = NSMakeRange(0, [attributeLeadString length]);
    [attributeLeadString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    return attributeLeadString;
}else{
    NSDictionary *attributeLeadColor = @{NSForegroundColorAttributeName:leadColor,NSFontAttributeName:attributeFont1};

    NSMutableAttributedString *attributeLeadString = [[NSMutableAttributedString alloc]
                                                      initWithString:leadString
                                                      attributes:attributeLeadColor];
    NSDictionary *attributeAppendColor = @{NSForegroundColorAttributeName:appendColor,NSFontAttributeName:attributeFont2};


    NSAttributedString *attributeAppendString = [[NSAttributedString alloc]
                                                 initWithString:appendString
                                                 attributes:attributeAppendColor];
    [attributeLeadString appendAttributedString:attributeAppendString];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing; // 调整行间距
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    NSRange range = NSMakeRange(0, [attributeLeadString length]);
    [attributeLeadString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    return attributeLeadString;
}
}
//***  获取字符宽度
+(float)widhForString:(NSString*)value fountSize:(float)fountsize{
return
[value boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fountsize]} context:nil].size.width;
}
//***  获取字符高度
+(float)heightForString:(NSString*)value fountSize:(float)fountsize{
return  [value boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fountsize]} context:nil].size.height;
}
//计算行数
+(CGFloat)getLineNum:(NSString*)str  font:(UIFont*)font labelWidth:(CGFloat)width{
if (str.length<1)
{
    return 0;
}

CGFloat oneRowHeight = [@"占位" sizeWithAttributes:@{NSFontAttributeName:font}].height;
CGSize textSize = [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
CGFloat rows = textSize.height / oneRowHeight;

return rows;
}

//切圆角
+ (void)cutRoundView:(UIView *)view{
CGFloat corner = CGRectGetWidth(view.frame) / 2;
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(corner, corner)];
shapeLayer.path = path.CGPath;
view.layer.mask = shapeLayer;
}
排版不易,觉得有用的就给个喜欢吧,有问题欢迎大家随时咨询。
上一篇 下一篇

猜你喜欢

热点阅读