GlobalMethod+UI.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. //
  2. // GlobalMethod+UI.m
  3. // 乐销
  4. //
  5. // Created by 隋林栋 on 2016/12/16.
  6. // Copyright © 2016年 ping. All rights reserved.
  7. //
  8. #import "GlobalMethod+UI.h"
  9. //数据大小
  10. #import <limits.h>
  11. @implementation GlobalMethod (UI)
  12. #pragma mark 计算label size
  13. + (CGFloat)fetchHeightFromLabel:(UILabel *)label{
  14. return [self fetchHeightFromLabel:label heightLimit:10000];
  15. }
  16. + (CGFloat)fetchHeightFromLabel:(UILabel *)label heightLimit:(CGFloat )height{
  17. if (label == nil) {
  18. return 0;
  19. }
  20. NSAttributedString * attributeString = [[NSAttributedString alloc]initWithString:!isStr(label.text)? @"A":label.text attributes:@{NSFontAttributeName: label.font}];
  21. CGRect rect =[attributeString boundingRectWithSize:CGSizeMake(label.width, height) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
  22. CGFloat num_height_return = rect.size.height+1;
  23. //限制行数
  24. if (label.numberOfLines != 0) {
  25. attributeString = [[NSAttributedString alloc]initWithString:@"A" attributes:@{NSFontAttributeName: label.font}];
  26. rect =[attributeString boundingRectWithSize:CGSizeMake(label.width, height) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
  27. num_height_return = num_height_return >label.numberOfLines*rect.size.height?label.numberOfLines*rect.size.height:num_height_return;
  28. }
  29. return ceil(num_height_return) ;
  30. }
  31. + (CGFloat)fetchWidthFromLabel:(UILabel *)label{
  32. NSString * strContent = label.text == nil ? @"":label.text;
  33. UIFont * font = label.font;
  34. NSAttributedString * attributeString = [[NSAttributedString alloc]initWithString:strContent attributes:@{NSFontAttributeName: font}];
  35. CGRect rect =[attributeString boundingRectWithSize:CGSizeMake(1000, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
  36. // NSLog(@"ceil Before: %lf",rect.size.width);
  37. return ceil(rect.size.width);
  38. }
  39. + (CGFloat)fetchWidthFromButton:(UIButton *)btn{
  40. UILabel * label = [UILabel new];
  41. label.font = btn.titleLabel.font;
  42. label.text = btn.titleLabel.text;
  43. return [self fetchWidthFromLabel:label];
  44. }
  45. //设置label
  46. + (void)setLabel:(UILabel *)label
  47. widthLimit:(CGFloat )widthLimit
  48. numLines:(NSInteger)numLines
  49. fontNum:(CGFloat)fontNum
  50. textColor:(UIColor *)textColor
  51. aligent:(NSTextAlignment )aligent
  52. text:(NSString *)text
  53. bgColor:(UIColor *)color{
  54. label.numberOfLines = numLines;
  55. label.font = [UIFont systemFontOfSize:fontNum];
  56. label.textColor = textColor == nil? COLOR_LABEL : textColor;
  57. label.textAlignment = aligent;
  58. label.backgroundColor = color == nil?[UIColor clearColor]:color;
  59. label.text = UnPackStr(text);
  60. CGFloat widthMAX= [self fetchWidthFromLabel:label];
  61. // NSLog(@"widthMAX : %lf",widthMAX);
  62. if (widthLimit != 0 ) {
  63. if (widthMAX < widthLimit) {
  64. label.width = widthMAX;
  65. }else {
  66. label.width = widthLimit;
  67. }
  68. }else {
  69. label.width = widthMAX;
  70. }
  71. label.height = [self fetchHeightFromLabel:label];
  72. }
  73. + (void)setLabel:(UILabel *)label
  74. widthLimit:(CGFloat )widthLimit
  75. numLines:(NSInteger)numLines
  76. fontNum:(CGFloat)fontNum
  77. textColor:(UIColor *)textColor
  78. text:(NSString *)text{
  79. [self setLabel:label widthLimit:widthLimit numLines:numLines fontNum:fontNum textColor:textColor aligent:label.textAlignment text:text bgColor:[UIColor clearColor]];
  80. }
  81. + (void)resetLabel:(UILabel *)label
  82. attributeString:(NSAttributedString *)text
  83. widthLimit:(CGFloat )widthLimit{
  84. label.attributedText = text;
  85. CGRect rect =[text boundingRectWithSize:CGSizeMake(widthLimit, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
  86. label.width = MIN(CGRectGetWidth(rect), widthLimit?:CGFLOAT_MAX);
  87. //限制行数
  88. label.height = [self fetchHeightFromLabel:label heightLimit:CGFLOAT_MAX];
  89. // label.height = rect.size.height+1;
  90. }
  91. + (CGFloat)fetchHeightFromFont:(NSInteger)fontNum{
  92. NSAttributedString *attributeString = [[NSAttributedString alloc]initWithString:@"A" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontNum]}];
  93. CGRect rect =[attributeString boundingRectWithSize:CGSizeMake(INTMAX_MAX, INTMAX_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
  94. return rect.size.height;
  95. }
  96. //设置圆角
  97. + (void)setRoundView:(UIView *)iv color:(UIColor *)color
  98. {
  99. [self setRoundView:iv color:color numRound:4 width:4];
  100. }
  101. //设置圆角
  102. + (void)setRoundView:(UIView *)iv color:(UIColor *)color numRound:(CGFloat)numRound width:(CGFloat)width
  103. {
  104. iv.layer.cornerRadius = numRound;//圆角设置
  105. iv.layer.masksToBounds = YES;
  106. [iv.layer setBorderWidth:width];
  107. iv.layer.borderColor = color.CGColor;
  108. }
  109. //设置textfield左间距
  110. + (void)setTextFileLeftPadding:(UITextField *)ut leftPadding:(float)leftPadding{
  111. CGRect frame = ut.frame;
  112. frame.size.width = leftPadding;
  113. UIView *leftV = [[UIView alloc] initWithFrame:frame];
  114. ut.leftViewMode = UITextFieldViewModeAlways;
  115. ut.leftView = leftV;
  116. }
  117. //设置日期格式
  118. + (NSString *)exchangeDate:(NSDate *)date formatter:(NSString *)formate{
  119. if (date == nil || formate == nil) {
  120. return @"";
  121. }
  122. NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  123. NSDateFormatter *dateFormatter = threadDictionary[@"myDateFormatter"];
  124. if(!dateFormatter){
  125. @synchronized(self){
  126. if(!dateFormatter){
  127. dateFormatter = [[NSDateFormatter alloc] init];
  128. [dateFormatter setAMSymbol:@"上午"];
  129. [dateFormatter setPMSymbol:@"下午"];
  130. threadDictionary[@"myDateFormatter"] = dateFormatter;
  131. }
  132. }
  133. }
  134. // 必填字段
  135. // static NSDateFormatter *dateFormatter = nil;
  136. // if (dateFormatter == nil) {
  137. // dateFormatter = [[NSDateFormatter alloc] init];
  138. // [dateFormatter setAMSymbol:@"上午"];
  139. // [dateFormatter setPMSymbol:@"下午"];
  140. // }
  141. [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];//解决8小时时间差问题
  142. //设定时间格式,这里可以设置成自己需要的格式
  143. [dateFormatter setDateFormat:formate];
  144. //用[NSDate date]可以获取系统当前时间
  145. NSString *currentDateStr = [dateFormatter stringFromDate:date];
  146. return currentDateStr;
  147. }
  148. //设置日期格式
  149. + (NSDate *)exchangeStringToDate:(NSString *)string formatter:(NSString *)formate{
  150. if (!isStr(string) || !isStr(formate)) {
  151. return nil;
  152. }
  153. NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  154. NSDateFormatter *dateFormatter = threadDictionary[@"myStrToDateformatter"];
  155. if(!dateFormatter){
  156. @synchronized(self){
  157. if(!dateFormatter){
  158. dateFormatter = [[NSDateFormatter alloc] init];
  159. threadDictionary[@"myStrToDateformatter"] = dateFormatter;
  160. }
  161. }
  162. }
  163. // // 必填字段
  164. // static NSDateFormatter *dateFormatter = nil;
  165. // if (dateFormatter == nil) {
  166. // dateFormatter = [[NSDateFormatter alloc] init];
  167. // }
  168. //设定时间格式,这里可以设置成自己需要的格式
  169. [dateFormatter setDateFormat:formate];
  170. //用[NSDate date]可以获取系统当前时间
  171. return [dateFormatter dateFromString:string];
  172. }
  173. //转换日期格式
  174. + (NSString *)exchangeString:(NSString *)string fromFormatter:(NSString *)formateFrom toFormatter:(NSString *)formateTo{
  175. if (!isStr(string)) {
  176. return @"";
  177. }
  178. NSDate * date= [self exchangeStringToDate:string formatter:formateFrom];
  179. if (date) {
  180. return [self exchangeDate:date formatter:formateTo];
  181. }
  182. return @"";
  183. }
  184. + (NSDate *)exchangeString:(NSString *)str formatter:(NSString *)formate{
  185. if (str == nil || formate == nil) {
  186. return [NSDate date];
  187. }
  188. NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  189. NSDateFormatter *dateFormatter = threadDictionary[@"myStrDateFormatter"];
  190. if(!dateFormatter){
  191. @synchronized(self){
  192. if(!dateFormatter){
  193. dateFormatter = [[NSDateFormatter alloc] init];
  194. threadDictionary[@"myStrDateFormatter"] = dateFormatter;
  195. }
  196. }
  197. }
  198. // 必填字段
  199. // static NSDateFormatter *dateFormatter = nil;
  200. //
  201. // if (dateFormatter == nil) {
  202. // dateFormatter = [[NSDateFormatter alloc] init];
  203. // }
  204. //设定时间格式,这里可以设置成自己需要的格式
  205. [dateFormatter setDateFormat:formate];
  206. //用[NSDate date]可以获取系统当前时间
  207. NSDate *currentDate = [dateFormatter dateFromString:str];
  208. return currentDate;
  209. }
  210. + (NSString *)exchangeDateStringResponse:(NSString *)str formatter:(NSString *)formate{
  211. if (!isStr(str)) {
  212. return @"";
  213. }
  214. NSRange range = [str rangeOfString:@"0001"];
  215. if (range.location != NSNotFound) {
  216. return @"";
  217. }
  218. range = [str rangeOfString:@"."];
  219. if (range.length > 0) {
  220. str = [str substringToIndex:range.location];
  221. }
  222. // NSArray * aryDate = [str componentsValidSeparatedByString:@"T"];
  223. // NSDate * dateYear = [self exchangeString:aryDate.firstObject formatter:@"yyyy-MM-dd"];
  224. // NSDate * dateHour = [self exchangeString:aryDate.lastObject formatter:@"HH-mm-ss"];
  225. // NSString * strDate = [NSString stringWithFormat:@"%@ %@",[self exchangeDate:dateYear formatter:@"yyyy-MM-dd"],[self exchangeDate:dateHour formatter:@"HH-mm-ss"]];
  226. NSDate * dateRight = [self exchangeString:str formatter:@"yyyy-MM-dd HH-mm-ss"];
  227. NSString * strReturn = [self exchangeDate:dateRight formatter:formate];
  228. return isStr(strReturn)?strReturn:str;
  229. }
  230. //获取当前时间戳
  231. + (NSString *)fetchTimeStamp{
  232. return [NSString stringWithFormat:@"%.f",[[NSDate date] timeIntervalSince1970]];
  233. }
  234. //获取时间
  235. + (NSString *)fetchTimeStampWithStr:(NSString *)str formatter:(NSString *)formatter{
  236. NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:[str doubleValue]/1000+3600*8];
  237. return [self exchangeDate:date1 formatter:formatter];
  238. }
  239. #pragma mark 比较两个时间戳相差天数,takeCarTime:传的时间
  240. + (NSString *)getHour:(NSString *)takeCarTime systemTime:(NSString *)systemTime
  241. {
  242. NSDate *DRstartDate = [NSDate dateWithTimeIntervalSince1970:[takeCarTime doubleValue]/1000+3600*8];
  243. NSDate *DRendDate = [NSDate dateWithTimeIntervalSince1970:[systemTime doubleValue]+3600*8];
  244. NSCalendar *gregorian = [[ NSCalendar alloc ] initWithCalendarIdentifier : NSCalendarIdentifierGregorian];
  245. NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  246. NSDateComponents *components = [gregorian components:unitFlags fromDate:DRendDate toDate:DRstartDate options:0];
  247. // 获得某个时间的年月日时分秒
  248. // NSDateComponents *createDateCmps = [calendar components:unit fromDate:DRstartDate];
  249. // NSDateComponents *nowCmps = [calendar components:unit fromDate:DRendDate];
  250. NSLog(@"剩余%ld天,%ld小时%ld分", components.day ,components.hour, components.minute);
  251. NSLog(@"相差%ld小时",components.hour);
  252. if (components.day>1||(components.day==1&&components.hour!=0)) {
  253. return [NSString stringWithFormat:@"%ld天",(long)components.day];
  254. }else{
  255. if (components.hour>1) {
  256. return [NSString stringWithFormat:@"%ld小时",(long)components.hour];
  257. }else{
  258. if (components.minute>1) {
  259. return [NSString stringWithFormat:@"%ld分钟",(long)components.minute];
  260. }else{
  261. return @"1分钟";
  262. }
  263. }
  264. }
  265. }
  266. // exhcnage status bar
  267. + (void)exchangeStatusBar:(UIStatusBarStyle) statusBarStyle{
  268. [GlobalData sharedInstance].statusBarStyle = statusBarStyle;
  269. UIViewController * lastVC = GB_Nav.lastVC;
  270. [lastVC setNeedsStatusBarAppearanceUpdate];
  271. }
  272. + (void)exchangeStatusBarHidden:(BOOL)hidden{
  273. [GlobalData sharedInstance].statusHidden = hidden;
  274. UIViewController * lastVC = GB_Nav.lastVC;
  275. [lastVC setNeedsStatusBarAppearanceUpdate];
  276. }
  277. //红色的数字
  278. + (void)exchangeLabel:(UILabel *)label positiveCount:(int)count {
  279. label.hidden = count <=0;
  280. if (!label ) return;
  281. count = count>99?99:count;
  282. NSString * strNum = count < 10? @"AAA": @"AAAA";
  283. [GlobalMethod setLabel:label widthLimit:0 numLines:0 fontNum:12 textColor:[UIColor whiteColor] text:strNum];
  284. label.backgroundColor = [UIColor redColor];
  285. [GlobalMethod setRoundView:label color:[UIColor clearColor] numRound:label.height / 2.0- 2 width:0];
  286. label.text = [NSString stringWithFormat:@"+%d",count];
  287. label.textAlignment = NSTextAlignmentCenter;
  288. }
  289. + (void)exchangeLabel:(UILabel *)label count:(int)count {
  290. label.hidden = count <=0;
  291. if (!label ) return;
  292. count = count>99?99:count;
  293. NSString * strNum = count < 10? @"AA": @"AAA";
  294. [GlobalMethod setLabel:label widthLimit:0 numLines:0 fontNum:12 textColor:[UIColor whiteColor] text:strNum];
  295. label.backgroundColor = [UIColor redColor];
  296. [GlobalMethod setRoundView:label color:[UIColor clearColor] numRound:label.height / 2.0 width:0];
  297. label.text = [NSString stringWithFormat:@"%d",count];
  298. label.textAlignment = NSTextAlignmentCenter;
  299. }
  300. //设置行间距
  301. +(void )setAttributeLabel:(UILabel *)label content:(NSString *)content width:(CGFloat)width
  302. {
  303. [self setAttributeLabel:label content:content width:width lineSpace:7];
  304. }
  305. +(void)setAttributeLabel:(UILabel *)label content:(NSString *)content width:(CGFloat)width lineSpace:(CGFloat)line{
  306. label.width = width;
  307. NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:content];
  308. NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  309. [paragraphStyle setLineSpacing:line];
  310. [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
  311. [label setAttributedText:attributedString];
  312. [label sizeToFit];
  313. }
  314. //获取审批cell
  315. + (CGFloat)resetCellView:(UIView *)view withArray:(NSArray *)array{
  316. return [self resetView:view withArray:array];
  317. }
  318. //sectionHeaderView
  319. +(UIView *)resetTitle:(NSString *)title{
  320. if (!isStr(title)) {
  321. return nil;
  322. }
  323. UIView *contentView = [[UIView alloc] init];
  324. contentView.backgroundColor = COLOR_ADDRESS;
  325. contentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 30);
  326. UILabel *label = [UILabel new];
  327. [GlobalMethod setLabel:label widthLimit:0 numLines:1 fontNum:F(14) textColor:COLOR_999 text:@""];
  328. label.backgroundColor = [UIColor clearColor];
  329. [contentView addSubview:label];
  330. [label fitTitle:UnPackStr(title) variable:SCREEN_WIDTH-20];
  331. label.leftCenterY = XY(10,contentView.height/2.0);
  332. return contentView;
  333. }
  334. //复制内容到剪切板
  335. + (void)copyToPlte:(NSString *)str{
  336. if (!isStr(str)) {
  337. return;
  338. }
  339. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  340. pasteboard.string = str;
  341. }
  342. //显示编辑提示
  343. + (void)showEditAlert:(void (^)(void))block view:(UIView *)view{
  344. ModelBtn * modelDismiss = [ModelBtn modelWithTitle:@"取消" imageName:nil highImageName:nil tag:TAG_LINE color:[UIColor redColor]];
  345. modelDismiss.blockClick = block;
  346. ModelBtn * modelConfirm = [ModelBtn modelWithTitle:@"确认" imageName:nil highImageName:nil tag:TAG_LINE color:COLOR_BLUE];
  347. modelConfirm.blockClick = ^(void){
  348. [GB_Nav popViewControllerAnimated:true];
  349. };
  350. // [BaseAlertView initWithTitle:@"确认取消编辑?" content:@"返回将清除编辑的内容" aryBtnModels:@[modelDismiss,modelConfirm] viewShow:view];
  351. }
  352. //显示编辑提示dismissBlock与ConfirmBlock
  353. + (void)showEditAlertDismiss:(void (^)(void))dismissblock confirm:(void (^)(void))confirmblock view:(UIView *)view{
  354. ModelBtn * modelDismiss = [ModelBtn modelWithTitle:@"取消" imageName:nil highImageName:nil tag:TAG_LINE color:[UIColor redColor]];
  355. modelDismiss.blockClick = dismissblock;
  356. ModelBtn * modelConfirm = [ModelBtn modelWithTitle:@"确认" imageName:nil highImageName:nil tag:TAG_LINE color:COLOR_TEXT];
  357. modelConfirm.blockClick = confirmblock;
  358. [BaseAlertView initWithTitle:@"确认取消编辑?" content:@"返回将清除编辑的内容" aryBtnModels:@[modelDismiss,modelConfirm] viewShow:view];
  359. }
  360. //收键盘
  361. + (void)endEditing{
  362. UIWindow * window = [UIApplication sharedApplication].keyWindow;
  363. [window endEditing:true];
  364. }
  365. +(NSMutableAttributedString *)stringToAttributeString:(NSString *)text
  366. {
  367. //先把普通的字符串text转化生成Attributed类型的字符串
  368. NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];
  369. NSString * zhengze = @"\\[\\([a-zA-Z0-9\u4e00-\u9fa5]+\\)\\]"; //正则表达式 ,例如  [(呵呵)] = 😑
  370. NSError * error;
  371. NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];
  372. if (!re)
  373. {
  374. NSLog(@"%@😓",[error localizedDescription]);//打印错误😓
  375. }
  376. NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];//遍历字符串,获得所有的匹配字符串
  377. NSBundle *bundle = [NSBundle mainBundle];
  378. NSString * path = [bundle pathForResource:@"emj" ofType:@"plist"];  //plist文件,制作一个 数组,包含文字,表情图片名称
  379. NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];//获取 所有的数组
  380. //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
  381. for (int j =(int) arr.count - 1; j >= 0; j--) {
  382. //NSTextCheckingResult里面包含range
  383. NSTextCheckingResult * result = arr[j];
  384. for (int i = 0; i < face.count; i++) {
  385. if ([[text substringWithRange:result.range] isEqualToString:face[i][@"key"]])//从数组中的字典中取元素
  386. {
  387. NSString * imageName = [NSString stringWithString:face[i][@"picture"]];
  388. NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];//添加附件,图片
  389. //textAttachment.bounds=CGRectMake(0, 0, 20, 20);//调节表情大小
  390. textAttachment.image = [UIImage imageNamed:imageName];
  391. NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
  392. [attStr replaceCharactersInRange:result.range withAttributedString:imageStr];//替换未图片附件
  393. break;
  394. }
  395. }
  396. }
  397. return attStr;
  398. }
  399. + (BOOL)isLocationServiceOpen {
  400. if ([ CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
  401. return NO;
  402. } else
  403. return YES;
  404. }
  405. @end