You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1432 lines
54 KiB

//
// UICommon.m
// ChineseAgri-businesses
//
// Created by ecell on 2022/6/27.
//
#import "UICommon.h"
#import "AppDelegate.h"
#import <ReactiveObjC.h>
@implementation UICommon
#pragma mark - 快速创建UIView
/// 快速创建UIView
/// @param rect 坐标
/// @param backColor 背景颜色
/// @param cornerRadius 圆角大小
/// @param borderWidth 边框
/// @param borderColor 边框颜色
+ (UIView *)ui_view:(CGRect)rect
backgroundColor:(UIColor *)backColor
cornerRadius:(CGFloat)cornerRadius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor
{
UIView *view = [[UIView alloc]init];
view.frame = rect;
if (backColor) view.backgroundColor = backColor;
view.layer.borderWidth = borderWidth;
view.layer.borderColor = borderColor.CGColor;
view.layer.cornerRadius = cornerRadius;
//view.layer.masksToBounds = YES;
return view;
}
#pragma mark - 快速创建UILabel
/// 快速创建UILabel
/// @param rect 坐标
/// @param line 行数
/// @param align 字体位置
/// @param font 字体
/// @param textColor 字体颜色
/// @param text 内容
/// @param Radius 圆角大小
+ (UILabel *)ui_label:(CGRect)rect
lines:(NSInteger)line
align:(NSTextAlignment)align
font:(UIFont *)font
textColor:(UIColor *)textColor
text:(NSString *)text
Radius:(CGFloat)Radius
{
UILabel *label = [[UILabel alloc]init];
label.frame = rect;
label.textAlignment = align;
label.text = text?:@"";
label.textColor = textColor;
label.numberOfLines = line;
label.font = font;
label.layer.cornerRadius = Radius;
label.layer.masksToBounds = YES;
return label;
}
#pragma mark - 快速创建带内边距UILabel
/// 快速创建UILabel
/// @param rect 坐标
/// @param line 行数
/// @param align 字体位置
/// @param font 字体
/// @param textColor 字体颜色
/// @param text 内容
/// @param Radius 圆角大小
+ (MyUILabel *)ui_myLabel:(CGRect)rect
lines:(NSInteger)line
align:(NSTextAlignment)align
font:(UIFont *)font
textColor:(UIColor *)textColor
text:(NSString *)text
Radius:(CGFloat)Radius
{
MyUILabel *label = [[MyUILabel alloc]init];
label.frame = rect;
label.textAlignment = align;
label.text = text?:@"";
label.textColor = textColor;
label.numberOfLines = line;
label.font = font;
label.layer.cornerRadius = Radius;
label.layer.masksToBounds = YES;
return label;
}
/**
创建textView
@param rect 尺寸大小
@param textColor 文本颜色
@param font 字体
@param alignment 对齐方式
@param inputView 附加视图
@return 对象
*/
+ (UITextView *)ui_textView:(CGRect)rect textColor:(UIColor *)textColor backColor:(UIColor *)backColor font:(UIFont *)font alignment:(NSTextAlignment)alignment inputView:(UIView *)inputView
{
UITextView * textView = [[UITextView alloc] init];
if (backColor) textView.backgroundColor = backColor;
textView.frame = rect;
if (textColor) textView.textColor = textColor;
if (font) textView.font = font;
textView.textAlignment = alignment;
if (inputView) textView.inputAccessoryView = inputView;
return textView;
}
#pragma mark - 快速创建UIButton
/// 快速创建UIButton
/// @param rect 坐标
/// @param font 字体
/// @param normalColor 字体颜色
/// @param normalText 文字
/// @param click 点击事件
+ (UIButton *)ui_buttonSimple:(CGRect)rect
font:(UIFont *)font
normalColor:(UIColor *)normalColor
normalText:(NSString *)normalText
click:(void (^)(id x))click
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = rect;
if (font) btn.titleLabel.font = font;
if (normalColor) [btn setTitleColor:normalColor forState:UIControlStateNormal];
if (normalText) [btn setTitle:normalText forState:UIControlStateNormal];
[[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
if (click) {
click(x);
}
}];
return btn;
}
/**
创建tableView
@param rect 尺寸大小
@param style 样式
@param backColor 背景颜色
@param sth 代理对象
@param registerDic 注册内容
@return 对象
*/
+ (UITableView *)ui_tableView:(CGRect)rect style:(UITableViewStyle)style backColor:(UIColor *)backColor delegate:(id)sth registerDic:(NSDictionary *)registerDic
{
UITableView *tableView = [[UITableView alloc]initWithFrame:rect style:style];
tableView.frame = rect;
tableView.estimatedRowHeight = 0;
tableView.estimatedSectionHeaderHeight = 0;
tableView.estimatedSectionFooterHeight = 0;
tableView.delegate = sth;
tableView.dataSource = sth;
if (backColor) tableView.backgroundColor = backColor;
/*
NSDictionary *dic = @{
@"cell":@[@{@"nib":@""},@{@"class":@""}],
@"group":@[@{@"nib":@""},@{@"class":@""}]
};
*/
for (NSString *key in [registerDic allKeys]) {
if ([key isEqual:@"cell"]) {
NSArray *array = registerDic[key];
for (NSDictionary *dic in array) {
if (dic[@"nib"]) {
[tableView registerNib:[UINib nibWithNibName:dic[@"nib"] bundle:nil] forCellReuseIdentifier:dic[@"nib"]];
}else if (dic[@"class"]) {
[tableView registerClass:[NSClassFromString(dic[@"class"]) class] forCellReuseIdentifier:dic[@"class"]];
}
}
}else if ([key isEqual:@"group"]) {
NSArray *array = registerDic[key];
for (NSDictionary *dic in array) {
if (dic[@"nib"]) {
[tableView registerNib:[UINib nibWithNibName:dic[@"nib"] bundle:nil] forHeaderFooterViewReuseIdentifier:dic[@"nib"]];
}else if (dic[@"class"]) {
[tableView registerClass:[NSClassFromString(dic[@"class"]) class] forHeaderFooterViewReuseIdentifier:dic[@"class"]];
}
}
}
}
return tableView;
}
/// 创建指定圆角视图
/// @param rect 坐标
/// @param direction 圆角方向
/// @param toview 圆角View
/// @param sizeMake 圆角大小
+(UIView *) ui_uiViewFillet:(CGRect)rect
Viewdirection:(PYUIdirection)direction
toView:(UIView *)toview
sizeMake:(CGFloat)sizeMake
{
UIBezierPath *maskPath;
if (direction == PYUIdirectionTop)
{
maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(sizeMake, sizeMake)];
}
else if(direction == PYUIdirectionBotton)
{
maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerBottomRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(sizeMake, sizeMake)];
}
else if(direction == PYUIdirectionLeft)
{
maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(sizeMake, sizeMake)];
}
else if(direction == PYUIdirectionRight)
{
maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(sizeMake, sizeMake)];
}
else
{
maskPath = [UIBezierPath bezierPathWithRoundedRect:rect
byRoundingCorners:UIRectCornerTopRight |
UIRectCornerTopLeft |
UIRectCornerBottomRight |
UIRectCornerBottomLeft
cornerRadii:CGSizeMake(sizeMake, sizeMake)];
}
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
maskLayer.path = maskPath.CGPath;
toview.layer.mask = maskLayer;
return toview;
}
/// 指定圆角并带有颜色边框
/// @param view 需要添加效果的视图
/// @param corner 圆角位置
/// @param cornerRadius 圆角大小
/// @param width 边框宽度
/// @param color 边框颜色
+ (void)setupView:(UIView *)view
corners:(UIRectCorner)corner
cornerRadius:(CGFloat)cornerRadius
borderWidth:(CGFloat)width
borderColor:(UIColor *)color
{
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
// 边框
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
borderLayer.lineWidth = width;
borderLayer.strokeColor = color.CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
// 指定圆角
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
byRoundingCorners:corner
cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
maskLayer.path = bezierPath.CGPath;
borderLayer.path = bezierPath.CGPath;
[view.layer insertSublayer:borderLayer atIndex:0];
[view.layer setMask:maskLayer];
}
#pragma mark - 快速创建textField
/**
创建textField
@param rect 尺寸大小
@param backColor 背景颜色
@param font 字体大小
@param maxNum 最大数量 传0表示没有限制
@param placeholderColor 默认字体颜色
@param placeholder 默认字
@param toMaxNum 设置了最大数量后回调
@param change 监听内容改变
@return 对象
*/
+ (UITextField *)ui_textField:(CGRect)rect textColor:(UIColor *)textColor backColor:(UIColor *)backColor font:(UIFont *)font maxTextNum:(NSInteger)maxNum placeholderColor:(UIColor *)placeholderColor placeholder:(NSString *)placeholder toMaxNum:(void(^)(UITextField *textField))toMaxNum change:(void(^)(UITextField *textField))change
{
UITextField *tf = [[UITextField alloc]init];
tf.returnKeyType = UIReturnKeyDone;
tf.frame = rect;
tf.backgroundColor = backColor;
tf.font = font;
if (textColor) tf.textColor = textColor;
//默认字
tf.placeholder = placeholder ?:@"";
//[tf setValue:placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
//tf.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"placeholder" attributes:@{NSForegroundColorAttributeName: [UIColor darkGrayColor], NSFontAttributeName: Font_(13)}];
if (maxNum > 0) {
[[tf.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
return value.length >= maxNum;
}] subscribeNext:^(NSString * _Nullable x) {
tf.text = [x substringToIndex:maxNum];
if (toMaxNum) {
toMaxNum(tf);
}
}];
}
[[tf rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
if (change) {
change(tf);
}
}];
return tf;
}
/**
创建图片
@param rect 尺寸大小
@param name 本地图片名称 传nil则不赋值
@return 对象
*/
+ (UIImageView *)ui_imageView:(CGRect)rect fileName:(NSString *)name
{
UIImageView *img = [[UIImageView alloc] init];
img.frame = rect;
if (name) {
img.image = [UIImage imageNamed:name];
}
return img;
}
/// 设置按钮文字在图片的下面
+ (void)setTitleAndImage:(UIButton *)btn :(CGFloat)heights
{
[btn setTitleEdgeInsets:
UIEdgeInsetsMake(btn.frame.size.height/heights,
(btn.frame.size.width-btn.titleLabel.intrinsicContentSize.width)/2-btn.imageView.frame.size.width,
0,
(btn.frame.size.width-btn.titleLabel.intrinsicContentSize.width)/2)];
[btn setImageEdgeInsets:
UIEdgeInsetsMake(0,
(btn.frame.size.width-btn.imageView.frame.size.width)/2,
btn.titleLabel.intrinsicContentSize.height,
(btn.frame.size.width-btn.imageView.frame.size.width)/2)];
}
/// 带XIB界面跳转
+(UIViewController *)PusXibViewController:(UIViewController *)viewController :(NSString *)viewXibTitle
{
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
viewController = [sb instantiateViewControllerWithIdentifier:viewXibTitle];
[[self currentVC].navigationController pushViewController:viewController animated:YES];
return viewController;
}
/// 颜色转Image
/// @param color 颜色
+ (UIImage*)createImageWithColor:(UIColor*)color
{
CGRect rect = CGRectMake(0,0,1,10);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
/// 换算时分秒
/// @param totalSeconds 秒
/// @param type 换算类型 0:时分秒 1:分秒 2:其他
+ (NSString *)timeFormatted:(NSInteger)totalSeconds
type:(int)type
{
totalSeconds = totalSeconds/1000;
NSInteger seconds = totalSeconds % 60;
NSInteger minutes = (totalSeconds / 60) % 60;
NSInteger hours = totalSeconds / 3600;
if(type == 0)
return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours, (long)minutes, (long)seconds];
else if(type == 1)
return hours > 0 ? [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours, (long)minutes, (long)seconds] : [NSString stringWithFormat:@"%02ld:%02ld", (long)minutes, (long)seconds];
else
return [NSString stringWithFormat:@"%ld", (long)minutes];
}
/// UIlabel 文字多种颜色
/// @param title 文字
/// @param index 变换颜色开始位
/// @param fonts 字体
/// @param colors 颜色
+ (NSAttributedString *)attributedTextWith:(NSString *)title
index:(NSInteger)index
fonts:(UIFont *)fonts
color:(UIColor *)colors
{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:title];
[str addAttribute:NSForegroundColorAttributeName value:colors range:NSMakeRange(0,index)];
// [str addAttribute:NSForegroundColorAttributeName value:KKMainSubColor range:NSMakeRange(index,title.length-index)];
[str addAttribute:NSFontAttributeName value:fonts range:NSMakeRange(0, index)];
[str addAttribute:NSFontAttributeName value:fonts range:NSMakeRange(index, title.length-index)];
return str;
}
/// UIlabel 某个位置文字多种颜色
/// @param title 文字
/// @param index 变换颜色开始位
/// @param toindex 结束位
/// @param fonts 字体
/// @param colors 颜色
/// @param tocolors 其他字段颜色
/// @param line 间距
/// @param TextAlignment 字体位置
+ (NSAttributedString *)attributedTextWiths:(NSString *)title
index:(NSInteger)index
toindex:(NSInteger)toindex
fonts:(UIFont *)fonts
color:(UIColor *)colors
tocolor:(UIColor *)tocolors
line:(CGFloat)line
TextAlignment:(NSTextAlignment)TextAlignment
{
NSRange symbolRange = [title rangeOfString:@""];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:title];
[str addAttribute:NSForegroundColorAttributeName value:colors range:NSMakeRange(index,toindex)];
[str addAttribute:NSFontAttributeName value:fonts range:NSMakeRange(index, toindex)];
[str addAttribute:NSForegroundColorAttributeName value:tocolors range:NSMakeRange(toindex,title.length-toindex)];
if (symbolRange.location != NSNotFound) {
[str addAttribute:NSFontAttributeName value:Font_(12) range:NSMakeRange(symbolRange.location, symbolRange.length)];
}
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = line;
paragraphStyle.alignment = TextAlignment;
[str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
return str;
}
+ (NSString *)getShowDateWithTime:(NSString *)time
{
NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:[time integerValue]/1000.0/1000];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MM-dd hh:mm";
NSString *timeStr = [dateFormatter stringFromDate:timeDate];
return timeStr;
}
+ (void)BtnLaye:(UIButton *)btn colors:(UIColor *)BtnColor BtnRadius:(CGFloat)BtnRadius
{
[btn setBackgroundColor:BtnColor];
btn.layer.cornerRadius = BtnRadius;
// btn.layer.shadowOffset = CGSizeMake(0, 4); //阴影的偏移量
// btn.layer.shadowOpacity = 0.8; //阴影的不透明度
// btn.layer.shadowColor = BtnColor.CGColor;//阴影的颜色
}
/// 成功提示框
/// @param text 提示问题
+ (void)MessageSuccessText:(NSString *)text isImg:(BOOL)isImg
{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (!isImg)
[EasyTextView showText:text config:^EasyTextConfig *{
EasyTextConfig *config = [EasyTextConfig shared];
config.titleColor = KKWhiteColorColor;
config.bgColor = RGBA(0, 0, 0, .8);
config.shadowColor = KKClearColor;
return config;
}];
else
{
[EasyTextView showSuccessText:text config:^EasyTextConfig *{
EasyTextConfig *config = [EasyTextConfig shared];
config.titleColor = KKWhiteColorColor;
config.bgColor = RGBA(0, 0, 0, .8);
config.shadowColor = KKClearColor;
return config;
}];
}
});
});
}
/// 错误提示框
/// @param text 提示文字
+ (void)MessageErrorText:(NSString *)text
{
[self resignKeyboard];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[EasyTextConfig shared].titleColor = KKTextBlackColor;
[EasyTextConfig shared].bgColor = KKGrey219;
[EasyTextView showInfoText:text config:^EasyTextConfig *{
EasyTextConfig *config = [EasyTextConfig shared];
config.titleColor = KKWhiteColorColor;
config.bgColor = RGBA(0, 0, 0, .8);
config.shadowColor = KKClearColor;
config.setStatusType(TextStatusTypeUndefine);
return config;;
}];
});
});
}
/// 加载提示框
/// @param text 提示文字
+ (void)MessageUpload:(NSString *)text
{
[self resignKeyboard];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[EasyLoadingView showLoadingText:text config:^EasyLoadingConfig *{
EasyLoadingConfig *config = [EasyLoadingConfig shared];
config.tintColor = KKWhiteColorColor;
config.bgColor = RGBA(0, 0, 0, .8);
//config.shadowColor = KKClearColor;
return config;
}];
});
});
}
/// 隐藏提示框
+ (void)HidenLoading
{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[EasyLoadingView hidenLoading];
});
});
}
/// 指定字符大小
/// @param text 内容
+ (NSAttributedString *)labelFontSize:(NSString *)text
{
NSRange symbolRange = [text rangeOfString:@"条轨迹"];
NSRange symbolRange1 = [text rangeOfString:@""];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];
if (symbolRange.location != NSNotFound) {
[string addAttribute:NSFontAttributeName value:FontADA_(13) range:NSMakeRange(symbolRange.location, symbolRange.length)];
[string addAttribute:NSForegroundColorAttributeName value:KKGrey121 range:NSMakeRange(symbolRange.location, symbolRange.length)];
}
if (symbolRange1.location != NSNotFound) {
[string addAttribute:NSFontAttributeName value:Font_(12) range:NSMakeRange(symbolRange1.location, symbolRange1.length)];
[string addAttribute:NSForegroundColorAttributeName value:RGB(255, 175, 147) range:NSMakeRange(symbolRange1.location, symbolRange1.length)];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;
paragraphStyle.alignment = NSTextAlignmentCenter;
[string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
}
// if (RMBRange.location != NSNotFound )
// {
// [string addAttribute:NSFontAttributeName value:FontADA_(10) range:NSMakeRange(RMBRange.location, RMBRange.length)];
// [string addAttribute:NSForegroundColorAttributeName value:RGB(179, 179, 179) range:NSMakeRange(RMBRange.location, RMBRange.length)];
// }
// if (yueRange.location != NSNotFound )
// {
// [string addAttribute:NSFontAttributeName value:FontADA_(13) range:NSMakeRange(yueRange.location, yueRange.length)];
// }
// if (zuiRange.location != NSNotFound )
// {
// [string addAttribute:NSFontAttributeName value:FontADA_(14) range:NSMakeRange(zuiRange.location, zuiRange.length)];
// [string addAttribute:NSForegroundColorAttributeName value:KKGrey143 range:NSMakeRange(zuiRange.location, zuiRange.length)];
// }
// if (zhangRange.location != NSNotFound )
// {
// [string addAttribute:NSForegroundColorAttributeName value:KKGrey143 range:NSMakeRange(zhangRange.location, zhangRange.length)];
// }
// if (dieRange.location != NSNotFound )
// {
// [string addAttribute:NSForegroundColorAttributeName value:KKGrey143 range:NSMakeRange(dieRange.location, dieRange.length)];
// }
// if (xiaoRange.location != NSNotFound )
// {
// [string addAttribute:NSFontAttributeName value:FontADA_(12) range:NSMakeRange(xiaoRange.location, xiaoRange.length)];
// }
// if (yinsiRange14.location != NSNotFound)
// {
// NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
// paragraphStyle.lineSpacing = 5;
// paragraphStyle.alignment = NSTextAlignmentCenter;
// [string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
// [string addAttribute:NSFontAttributeName value:FontBold_(18) range:NSMakeRange(yinsiRange14.location, yinsiRange14.length)];
// }
return string;
}
/// 画删除线
/// @param label label
+ (void)drawLine:(UILabel *)label
{
NSString *oldPrice = label.text;
NSUInteger length = [oldPrice length];
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:oldPrice];
[attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(4, length-4)];
[attri addAttribute:NSStrikethroughColorAttributeName value:KKGrey219 range:NSMakeRange(4, length-4)];
[label setAttributedText:attri];
}
/// 画删除线
/// @param label label
+ (void)drawLine_ll:(UILabel *)label
{
NSString *oldPrice = label.text;
NSUInteger length = [oldPrice length];
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:oldPrice];
[attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
[attri addAttribute:NSStrikethroughColorAttributeName value:KKGrey219 range:NSMakeRange(0, length)];
[label setAttributedText:attri];
}
+ (UIViewController *)currentVC
{
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows)
{
if (tmpWin.windowLevel == UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
UIViewController *result = window.rootViewController;
while (result.presentedViewController)
{
result = result.presentedViewController;
}
if ([result isKindOfClass:[UITabBarController class]])
{
result = [(UITabBarController *)result selectedViewController];
}
if ([result isKindOfClass:[UINavigationController class]])
{
result = [(UINavigationController *)result topViewController];
}
return result;
}
+ (void)setBtnUpImageDownTitle:(UIButton *)btn
{
CGSize btnSize = btn.bounds.size;
UIImage *image = btn.imageView.image;
NSString *title = btn.titleLabel.text;
CGSize titleSize = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, btn.titleLabel.frame.size.height)
options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:btn.titleLabel.font} context:nil].size;
btn.titleEdgeInsets = UIEdgeInsetsMake(image.size.height, -image.size.width, 0, 0);
if ([CurrentSystemVersion doubleValue] >= 13.0)
{
btn.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height, btnSize.width / 2 - image.size.width/2 ,
0.5*titleSize.height, 0);
}
else
{
btn.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height, image.size.width/2 ,
0.5*titleSize.height, 0);
}
}
/// 之间戳转换成时间
/// @param time 时间戳
/// @param type 默认 年月日时分秒 MM:月日时分秒 DD:日时分秒 HH:时分秒
+ (NSString *)getTimeFromTimestamp:(NSString *)time type:(NSString *)type
{
//将对象类型的时间转换为NSDate类型
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:[time integerValue]];
//设置时间格式
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
if ([type isEqualToString:@"MM"])
[formatter setDateFormat:@"MM-dd HH:mm:ss"];
else if ([type isEqualToString:@"DD"])
[formatter setDateFormat:@"dd HH:mm:ss"];
else if ([type isEqualToString:@"HH"])
[formatter setDateFormat:@"HH:mm:ss"];
else if ([type isEqualToString:@"SS"])
[formatter setDateFormat:@"HH:mm"];
else if ([type isEqualToString:@"YMD"])
[formatter setDateFormat:@"YYYY-MM-dd HH"];
else if ([type isEqualToString:@"MDH"])
[formatter setDateFormat:@"MM-dd HH:mm"];
//将时间转换为字符串
NSString *timeStr=[formatter stringFromDate:myDate];
return timeStr;
}
/// 时间转换成几天、几小时、几分钟前
+ (NSString *)updateTimeForRow:(NSString *)createTimeString
{
// 获取当前时时间戳 1466386762.345715 十位整数 6位小数
NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
// 创建歌曲时间戳(后台返回的时间 一般是13位数字)
NSTimeInterval createTime = [createTimeString longLongValue];
// 时间差
NSTimeInterval time = currentTime - createTime;
NSInteger sec = time/60;
if (sec<60) {
return [NSString stringWithFormat:@"%ld分钟前",sec];
}
// 秒转小时
NSInteger hours = time/3600;
if (hours<24) {
return [NSString stringWithFormat:@"%ld小时前",hours];
}
//秒转天数
NSInteger days = time/3600/24;
if (days < 30) {
return [NSString stringWithFormat:@"%ld天前",days];
}
// //秒转月
// NSInteger months = time/3600/24/30;
// if (months < 12) {
// return [NSString stringWithFormat:@"%ld月前",months];
// }
// //秒转年
// NSInteger years = time/3600/24/30/12;
// return [NSString stringWithFormat:@"%ld年前",years];
return [self getTimeFromTimestamp:createTimeString type:@""];
}
/// 之间戳转换成时间
/// @param time 时间戳
+ (NSString *)getTimeFromTimestamp_n:(NSString *)time
{
//将对象类型的时间转换为NSDate类型
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:[time integerValue]/1000];
//设置时间格式
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd\nHH:mm:ss"];
//将时间转换为字符串
NSString *timeStr = [formatter stringFromDate:myDate];
return timeStr;
}
#pragma mark - Private Methods
/// 获取当前月的下一个月到某个日期内的所有月份
/// @param fromDateStr 起始月份 不传则获取半年内的月份
+ (NSArray *)returnSixYearAndMonth:(NSString*)fromDateStr
{
NSString *toDateStr = [self setupRequestMonth:1];
NSMutableArray *tempDateS = [NSMutableArray new];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyyMM"];
NSDate *fromDate = [formatter dateFromString:fromDateStr];
CGFloat monthNum = 0;
NSString *tempDateStr = fromDateStr.length > 0 ? fromDateStr : [self setupRequestMonth:-6];
NSDateComponents *comps = [NSDateComponents new];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
while (![tempDateStr isEqualToString:toDateStr])
{
[comps setMonth:monthNum];
NSDate *dateTime = [calendar dateByAddingComponents:comps toDate:fromDate options:0];
tempDateStr = [formatter stringFromDate:dateTime];
// TimeModel *model = [[TimeModel alloc] init];
// model.year = [tempDateStr substringToIndex:4];
// model.month = [tempDateStr substringWithRange:NSMakeRange(4, 2)];
// [tempDateS addObject:model];
monthNum++;
}
return [tempDateS copy];
}
/// 获取月份
/// @param monthNum -1为当前月份的前一个月,1为后一个月,以此类推
+ (NSString *)setupRequestMonth:(NSInteger)monthNum
{
NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMM"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
[lastMonthComps setMonth:monthNum];
NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
NSString *dateStr = [formatter stringFromDate:newdate];
NSLog(@"date str = %@", dateStr);
return dateStr;
}
/// 划虚线
+ (void)xuxian:(UIView *)view
{
UIBezierPath *maskPath=[[UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(3, 3)] bezierPathByReversingPath];
CAShapeLayer *border = [CAShapeLayer layer];
// 线条颜色
border.strokeColor = mainColor.CGColor;
border.masksToBounds = YES;
border.fillColor = nil;
border.path = maskPath.CGPath;
border.frame = view.bounds;
border.lineWidth = 1;
border.lineCap = @"square";
// 第一个是 线条长度 第二个是间距 nil时为实线
border.lineDashPattern = @[@2.6, @3];
[view.layer addSublayer:border];
}
/// json转字典
/// @param jsonString json
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil)
{
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if(err)
{
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
/// 字典转json
/// @param dic 字典
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
/// 判断字符串是否是json
/// @param jsonString 字符串
+ (BOOL)isJsonString:(NSString *)jsonString
{
if (jsonString.length < 2) return NO;
if (!([jsonString hasPrefix:@"{"] || [jsonString hasPrefix:@"["])) return NO;
// {:123 }:125 [: 91 ]:93
return [jsonString characterAtIndex:jsonString.length-1]-[jsonString characterAtIndex:0] == 2;
}
+ (void)setExtraCellLineHidden:(UITableViewCell *)cell
{
if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsMake(0, ScreenWidth, 0, 0)];
//UIEdgeInsetsZero
}
if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsMake(0, ScreenWidth, 0, 0)];
}
if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
[cell setPreservesSuperviewLayoutMargins:NO];
}
}
+ (void)setTavleViewlink:(UITableView *)tableview
distance:(CGFloat)distance
{
[tableview setSeparatorColor:RGB(240, 240, 240)];
if ([tableview respondsToSelector:@selector(setSeparatorInset:)])
tableview.separatorInset = UIEdgeInsetsMake(0, distance, 0, distance);
if ([tableview respondsToSelector:@selector(setLayoutMargins:)])
[tableview setLayoutMargins:UIEdgeInsetsMake(0, distance, 0, distance)];
}
/// 设置cell第一行和最后一行圆角
/// - Parameters:
/// - tableView: UITableView
/// - cell: cell
/// - indexPath: indexPath
/// - coutn: 总行数
/// - sizeH: 左右边距
+ (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
cellCoutn:(NSInteger)coutn
sizeH:(CGFloat)sizeH
{
// 圆角弧度半径
CGFloat cornerRadius = 12.f;
// 设置cell的背景色为透明,如果不设置这个的话,则原来的背景色不会被覆盖
cell.backgroundColor = UIColor.clearColor;
// 创建一个shapeLayer
CAShapeLayer *layer = [[CAShapeLayer alloc] init];
CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
// 创建一个可变的图像Path句柄,该路径用于保存绘图信息
CGMutablePathRef pathRef = CGPathCreateMutable();
// 获取cell的size
// 第一个参数,是整个 cell 的 bounds, 第二个参数是距左右两端的距离,第三个参数是距上下两端的距离
CGRect bounds = CGRectInset(cell.bounds, sizeH, 0);
// CGRectGetMinY:返回对象顶点坐标
// CGRectGetMaxY:返回对象底点坐标
// CGRectGetMinX:返回对象左边缘坐标
// CGRectGetMaxX:返回对象右边缘坐标
// CGRectGetMidX: 返回对象中心点的X坐标
// CGRectGetMidY: 返回对象中心点的Y坐标
// 这里要判断分组列表中的第一行,每组section的第一行,每组section的中间行
// CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
if (coutn == 1)
{
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
// 起始坐标为左下角,设为p,(CGRectGetMinX(bounds), CGRectGetMinY(bounds))为左上角的点,设为p1(x1,y1),(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点,设为p2(x2,y2)。然后连接p1和p2为一条直线l1,连接初始点p到p1成一条直线l,则在两条直线相交处绘制弧度为r的圆角。
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// 终点坐标为右下角坐标点,把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
// 初始起点为cell的左上角坐标
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// 添加一条直线,终点坐标为右下角坐标点并放到路径中去
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
return;
}
else
{
if (indexPath.row == 0) {
// 初始起点为cell的左下角坐标
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
// 起始坐标为左下角,设为p,(CGRectGetMinX(bounds), CGRectGetMinY(bounds))为左上角的点,设为p1(x1,y1),(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点,设为p2(x2,y2)。然后连接p1和p2为一条直线l1,连接初始点p到p1成一条直线l,则在两条直线相交处绘制弧度为r的圆角。
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// 终点坐标为右下角坐标点,把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
} else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
// 初始起点为cell的左上角坐标
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// 添加一条直线,终点坐标为右下角坐标点并放到路径中去
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
} else {
// 添加cell的rectangle信息到path中(不包括圆角)
CGPathAddRect(pathRef, nil, bounds);
}
}
// 把已经绘制好的可变图像路径赋值给图层,然后图层根据这图像path进行图像渲染render
layer.path = pathRef;
backgroundLayer.path = pathRef;
// 注意:但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
CFRelease(pathRef);
// 按照shape layer的path填充颜色,类似于渲染render
// layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
layer.fillColor = [UIColor whiteColor].CGColor;
// view大小与cell一致
UIView *roundView = [[UIView alloc] initWithFrame:bounds];
// 添加自定义圆角后的图层到roundView中
[roundView.layer insertSublayer:layer atIndex:0];
roundView.backgroundColor = UIColor.clearColor;
// cell的背景view
cell.backgroundView = roundView;
// 以上方法存在缺陷当点击cell时还是出现cell方形效果,因此还需要添加以下方法
// 如果你 cell 已经取消选中状态的话,那以下方法是不需要的.
UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
backgroundLayer.fillColor = [UIColor cyanColor].CGColor;
[selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
selectedBackgroundView.backgroundColor = UIColor.clearColor;
cell.selectedBackgroundView = selectedBackgroundView;
}
/// 颜色渐变
+ (UIImage *)setGradientBackgroundImg:(UIColor *)Color1
Color2:(UIColor *)Color2
Width:(CGFloat)Width
Height:(CGFloat)Height
{
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)Color1.CGColor, (__bridge id)Color2.CGColor];
gradientLayer.locations = @[@0, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 0, Width, Height);
gradientLayer.name = @"gradientLayer";
//生成一个image
UIGraphicsBeginImageContextWithOptions(CGSizeMake(Width, Height), YES, 0.0);
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//UIColor *backgroundColor = [UIColor colorWithPatternImage:img];
return img;
}
/// 颜色渐变
+ (UIColor *)setGradientBackgroundColor:(UIColor *)Color1
Color2:(UIColor *)Color2
Width:(CGFloat)Width
Height:(CGFloat)Height
{
CAGradientLayer *gl = [CAGradientLayer layer];
gl.frame = CGRectMake(16,144,343,72);
gl.startPoint = CGPointMake(0.03, 0);
gl.endPoint = CGPointMake(0.8, 3.05);
gl.colors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:239/255.0 blue:232/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor];
gl.locations = @[@(0), @(1.0f)];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)Color1.CGColor, (__bridge id)Color2.CGColor];
gradientLayer.locations = @[@0, @1.0];
// // 上下
// gradientLayer.startPoint = CGPointMake(0, 1.0);
// gradientLayer.endPoint = CGPointMake(0, 0);
// 左右
gradientLayer.startPoint = CGPointMake(0.03, 0);
gradientLayer.endPoint = CGPointMake(0.8, 3.05);
gradientLayer.frame = CGRectMake(0, 0, Width, Height);
gradientLayer.name = @"gradientLayer";
//生成一个image
UIGraphicsBeginImageContextWithOptions(CGSizeMake(Width, Height), YES, 0.0);
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIColor *backgroundColor = [UIColor colorWithPatternImage:img];
return backgroundColor;
}
void AfterDispatch(double delayInSeconds, dispatch_block_t _Nullable block) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}
//根据颜色返回图片
+(UIImage*)imageWithColor:(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 *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
//获取八位数code
+ (NSString *)getRandomEightCode
{
//自动生成8位随机密码
NSTimeInterval random=[NSDate timeIntervalSinceReferenceDate];
NSString *randomString = [NSString stringWithFormat:@"%.8f",random];
NSString *randompassword = [[randomString componentsSeparatedByString:@"."]objectAtIndex:1];
NSLog(@"randompassword:%@",randompassword);
return randompassword;
}
/// 震动反馈
+ (void)feedbackGenerator
{
UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
[generator prepare];
[generator impactOccurred];
}
// 消除键盘
+ (void)resignKeyboard
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.window endEditing:YES];
}
/// 给UITextField设置左右侧的图片
/// @param textField textField
/// @param leftImageName 左侧UIImageView图片名称
/// @param rightImageName 右侧UIButton图片名称
/// @param click 右侧UIButton点击事件回调
+ (void)setRightViewWithTextField:(UITextField *)textField
leftImageName:(NSString *)leftImageName
rightImageName:(NSString *)rightImageName
click:(void (^)(UITextField *textField))click
{
if (rightImageName.length > 0)
{
UIButton *rightView = [UIButton new];
[rightView setImage:ImageName_(rightImageName) forState:0];
rightView.frame = CGRectMake(0, 0, rightView.currentImage.size.width, rightView.currentImage.size.height);
rightView.size = rightView.currentImage.size;
[[rightView rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
if (click) {
click(textField);
}
}];
rightView.contentMode = UIViewContentModeCenter;
textField.rightView = rightView;
textField.leftViewMode = UITextFieldViewModeAlways;
}
if (leftImageName.length > 0)
{
UIImageView *leftView = [UIImageView new];
[leftView setImage:ImageName_(leftImageName)];
leftView.frame = CGRectMake(0, 0, leftView.image.size.width, leftView.image.size.height);
leftView.size = leftView.image.size;
leftView.contentMode = UIViewContentModeCenter;
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;
}
else
{
textField.rightView = nil;
textField.rightViewMode = UITextFieldViewModeAlways;
}
}
#pragma mark 二维码 URL获取 参数
+ (NSMutableDictionary *)getDicWithUrl:(NSString *)urlStr
{
//获取问号的位置,问号后是参数列表
NSRange range = [urlStr rangeOfString:@"?"];
if (range.location != NSNotFound) {
//获取参数列表
NSString *propertys = [urlStr substringFromIndex:(int)(range.location+1)];
//进行字符串的拆分,通过&来拆分,把每个参数分开
NSArray *subArray = [propertys componentsSeparatedByString:@"&"];
//把subArray转换为字典
//tempDic中存放一个URL中转换的键值对
NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
[subArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//在通过=拆分键和值
NSArray *dicArray = [obj componentsSeparatedByString:@"="];
if (dicArray.count >= 2) {
//给字典加入元素
[tempDic setObject:dicArray[1] forKey:dicArray[0]];
}
}];
return tempDic;
}
return nil;
}
//获取当前系统时间
+ (NSString *)getSysTime
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSString *timeString = [formatter stringFromDate:[NSDate date]];
return timeString;
}
+ (NSString *)getDateFormatWithStr:(NSString *)dateFormat date:(NSDate *)date
{
NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:dateFormat];
return [dateFormatter stringFromDate:date];
}
+ (NSString *)getDateFormatWithStr:(NSString *)dateFormat timeInterval:(NSTimeInterval)timeInterval
{
return [self getDateFormatWithStr:dateFormat date:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
}
+ (NSDate *)getDateWithStr:(NSString *)dateString dateFormat:(NSString *)dateFormat
{
dateString = [dateString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: dateFormat];
NSDate *destDate= [dateFormatter dateFromString:dateString];
return destDate;
}
+ (NSDate*)getTimeStrWithString:(NSString*)str
{
NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
// 创建一个时间格式化对象2023-01-07 16:56:08
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//设定时间的格式
NSDate * tempDate = [dateFormatter dateFromString:str];
//将字符串转换为时间对象
NSString*timeStr=[NSString stringWithFormat:@"%ld",(long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000returntimeStr;
return tempDate;
}
/// 获取文字宽度、高度
/// - Parameters:
/// - text: 需要计算的文字
/// - heights: 控件高度
/// - size: 文字大小
/// - type: w/W:宽度 ,h/H:高度
+ (CGRect)GetTextWidth:(NSString *)text ViewHeight:(CGFloat)heights fontSize:(UIFont *)size type:(NSString *)type
{
CGRect rect;
if ([type isEqualToString:@"W"] || [type isEqualToString:@"w"])
rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, heights) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:size} context:nil];
else
rect = [text boundingRectWithSize:CGSizeMake(heights, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:size} context:nil];
return rect;
}
/// 图片质量压缩
+(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
{
NSData *imageData = UIImageJPEGRepresentation(image, percent);
UIImage *newImage = [UIImage imageWithData:imageData];
return newImage;
}
/// 通过颜色获取图片
+ (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 [self setCornerWithImage:img cornerRadius:size.height/2];
}
+ (UIImage *)setCornerWithImage:(UIImage *)image cornerRadius:(CGFloat)cornerRadius
{
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:cornerRadius];
UIGraphicsBeginImageContext(image.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextAddPath(ctx, path.CGPath);
CGContextClip(ctx);
[image drawInRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
/// 获取当前一周的日期
+ (NSMutableArray *)backWeeksTimeNumber
{
NSDate *date = [[NSDate date] dateByAddingTimeInterval:- 7 * 24 * 3600];
//滚动后,算出当前日期所在的周(周一-周日)
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *comp = [gregorian components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:date];
NSInteger weekDay = [comp weekday]-1 ;
// 得到几号
NSInteger day = [comp day];
NSLog(@"weekDay:%ld day:%ld",weekDay,day);
// 计算当前日期和这周的星期一和星期天差的天数
long firstDiff,lastDiff;
if (weekDay == -1)
{ firstDiff = 1;
lastDiff = 0;
}
else
{
firstDiff = [gregorian firstWeekday] - weekDay;
lastDiff = 7 - weekDay;
}
NSMutableArray *currentWeeks = [self getCurrentWeeksWithFirstDiff:firstDiff lastDiff:lastDiff];
return currentWeeks;
}
+ (NSMutableArray *)getCurrentWeeksWithFirstDiff:(NSInteger)first lastDiff:(NSInteger)last
{
NSMutableArray *eightArr = [[NSMutableArray alloc] init];
for (NSInteger i = first; i < last + 1; i ++)
{
//从现在开始的24小时
NSTimeInterval secondsPerDay = i * 24*60*60;
NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateStr = [dateFormatter stringFromDate:curDate];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"zn_CN"]];
NSString *strTime = [NSString stringWithFormat:@"%@",dateStr];
[eightArr addObject:strTime];
}
return eightArr;
}
+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view fromColor:(UIColor *)fromHexColor toColor:(UIColor *)toHexColor
{
// CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = view.bounds;
// 创建渐变色数组,需要转换为CGColor颜色
gradientLayer.colors = @[(__bridge id)fromHexColor.CGColor,(__bridge id)toHexColor.CGColor];
// 设置渐变颜色方向,左上点为(0,0), 右下点为(1,1)
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 1);
// 设置颜色变化点,取值范围 0.0~1.0
gradientLayer.locations = @[@0,@1];
return gradientLayer;
}
/// 改变label文字行间距
/// @param text 内容
+ (NSAttributedString *)labelLinesHeight:(NSString *)text
height:(CGFloat)height
align:(NSTextAlignment)align
{
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = height;
paragraphStyle.alignment = align;
[string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
return string;
}
@end