ios 日常记录-不定时更新

1.一行代码收起键盘

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

2.取消tableview的分割线

TableView.separatorStyle = UITableViewCellAccessoryNone

3.取消头部视图跟随效果

//切换tableview的style  UITableViewStyleGrouped头部视图不跟随   

self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 50) style:UITableViewStyleGrouped]

4.解决tableview视图上移

方案一
self.automaticallyAdjustsScrollViewInsets = NO;// 默认是YES

方案二
self.edgesForExtendedLayout = UIRectEdgeNone;// 推荐使用

5.html字符串转换成富文本

NSAttributedString *att = [[NSAttributedString alloc] initWithData:[model.detail dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

通过设置控件的字体大小来改变字的大小,位置要放在给控件赋值之后

6.计算文本高度

-(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(kWidth-30,MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil];
    
    return rect.size;
}

7.获取点击cell的indexpath

//获取当前点击cell的row或者section
self.tableView.indexPathForSelectedRow.row
self.tableView.indexPathForSelectedRow.section

//获取当前点击cell的indexpath
self.mainView.indexPathsForSelectedRows

8.设置label不同位置字体大小和颜色

//设置不同字体颜色
-(void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    
    label.attributedText = str;
}

9.UITextView :启动时文字位置不从顶部开始

- (void)viewDidLayoutSubviews {
    [self.textView setContentOffset:CGPointZero animated:NO];
}

10.获取HTML字符串的文本信息

-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
        //去除空格 &nbsp;
        html = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    }
    return html;
}

11.隐藏导航栏返回按钮

隐藏
self.navigationItem.leftBarButtonItem.customView.hidden = YES;
显示
self.navigationItem.leftBarButtonItem.customView.hidden = NO;

12.QQ聊天背景图片拉伸方法

+ (UIImage *)resizeWithImage:(UIImage *)image{
    CGFloat top = image.size.height/2.0;
    CGFloat left = image.size.width/2.0;
    CGFloat bottom = image.size.height/2.0;
    CGFloat right = image.size.width/2.0;
    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(top, left, bottom, right)resizingMode:UIImageResizingModeStretch];
}

13.在控件内部取消键盘第一响应者

//在控件内部取消键盘第一响应者
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

14.获取cell在相对视图上的位置

NSIndexPath *index = [self.mainView indexPathForCell:cell];
CGRect rect = [self.mainView rectForRowAtIndexPath:index];
CGRect touchRct = [self.mainView convertRect:rect toView:self.view];

15.解决导航栏照片虚化放大

[self.rightBtn.widthAnchor constraintEqualToConstant:25].active = YES;
[self.rightBtn.heightAnchor constraintEqualToConstant:25].active = YES;

16.点击图片放大,再次点击缩小

/**
 * @brief 点击图片放大,再次点击缩小
 * @param avatarImageView 头像所在的imageView
 */
+(void)showImage:(UIImageView*)avatarImageView

{
    
    UIImage *image =avatarImageView.image;
    
    UIWindow *window =[UIApplication sharedApplication].keyWindow;
    UIView *backgroundView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, myWidth, myHeight)];
    
    oldframe =[avatarImageView convertRect:avatarImageView.bounds toView:window];
    
    backgroundView.backgroundColor =[UIColor blackColor];
    
    backgroundView.alpha =0.5;
    
    UIImageView *imageView =[[UIImageView alloc]initWithFrame:oldframe];
    
    imageView.image =image;
    
    imageView.tag =1;
    
    [backgroundView addSubview:imageView];
    
    [window addSubview:backgroundView];
    
    //点击图片缩小的手势
    
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    
    [backgroundView addGestureRecognizer:tap];
    
    
    
    [UIView animateWithDuration:0.3 animations:^{
        
        imageView.frame =CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        
        backgroundView.alpha =1;
        
    }];
    
}

+(void)hideImage:(UITapGestureRecognizer *)tap{
    
    UIView *backgroundView =tap.view;
    
    UIImageView *imageView =(UIImageView *)[tap.view viewWithTag:1];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        imageView.frame =oldframe;
        
        backgroundView.alpha =0;
        
        
        
    } completion:^(BOOL finished) {
        
        [backgroundView removeFromSuperview];
        
    }];
    
}

17.判断字符串时候含有键盘表情

//判断字符串时候含有键盘表情
+ (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 hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

//判断是否有emoji
-(BOOL)stringContainsEmoji
{
    __block BOOL returnValue = NO;
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self 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;
}

18 将输出日志打印到文件

- (void)redirectNSLogToDocumentFolder

{

 //如果已经连接Xcode调试则不输出到文件

 if(isatty(STDOUT_FILENO)) {

 return;

 }

 UIDevice *device = [UIDevice currentDevice];

 if([[device model] hasSuffix:@"Simulator"]){ //在模拟器不保存到文件中

 return;

 }

 //将NSlog打印信息保存到Document目录下的Log文件夹下

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"];

 NSFileManager *fileManager = [NSFileManager defaultManager];

 BOOL fileExists = [fileManager fileExistsAtPath:logDirectory];

 if (!fileExists) {

 [fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:nil];

 }

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

 [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];

 [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //每次启动后都保存一个新的日志文件中

 NSString *dateStr = [formatter stringFromDate:[NSDate date]];

 NSString *logFilePath = [logDirectory stringByAppendingFormat:@"/%@.log",dateStr];

 // 将log输入到文件

 freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);

 freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);

 //未捕获的Objective-C异常日志

 NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);

}

void UncaughtExceptionHandler(NSException* exception)

{

 NSString* name = [ exception name ];

 NSString* reason = [ exception reason ];

 NSArray* symbols = [ exception callStackSymbols ]; // 异常发生时的调用栈

 NSMutableString* strSymbols = [ [ NSMutableString alloc ] init ]; //将调用栈拼成输出日志的字符串

 for ( NSString* item in symbols )

 {

 [ strSymbols appendString: item ];

 [ strSymbols appendString: @"\r\n" ];

 }

 //将crash日志保存到Document目录下的Log文件夹下

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"];

 NSFileManager *fileManager = [NSFileManager defaultManager];

 if (![fileManager fileExistsAtPath:logDirectory]) {

 [fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:nil];

 }

 NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];

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

 [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];

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

 NSString *dateStr = [formatter stringFromDate:[NSDate date]];

 NSString *crashString = [NSString stringWithFormat:@"<- %@ ->[ Uncaught Exception ]\r\nName: %@, Reason: %@\r\n[ Fe Symbols Start ]\r\n%@[ Fe Symbols End ]\r\n\r\n", dateStr, name, reason, strSymbols];

 //把错误日志写到文件中

 if (![fileManager fileExistsAtPath:logFilePath]) {

 [crashString writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

 }else{

 NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:logFilePath];

 [outFile seekToEndOfFile];

 [outFile writeData:[crashString dataUsingEncoding:NSUTF8StringEncoding]];

 [outFile closeFile];

 }

 //把错误日志发送到邮箱

 // NSString *urlStr = [NSString stringWithFormat:@"[mailto://test@163.com?subject=bug](mailto:mailto://test@163.com?subject=bug)报告&body=感谢您的配合!<br><br><br>错误详情:<br>%@",crashString ];

 // NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

 // [[UIApplication sharedApplication] openURL:url];

}

//钱格式转换
- (NSString *)getAmountInWords:(NSString *)money{
    if (money.length == 0) {
        return @"";
    }
    if (money.floatValue == 0) {
        return @"零圆整";
    }
    //大写数字
    NSArray *upperArray = @[ @"零",@"壹",@"贰",@"叁",@"肆",@"伍",@"陆",@"柒",@"捌",@"玖" ];
    /** 整数部分的单位 */
    NSArray *measureArray = @[ @"", @"拾", @"佰", @"仟"];
    /** 整数部分的单位 */
    NSArray *intUnit = @[@"圆", @"万", @"亿"];
    /** 小数部分的单位 */
    NSArray *floatUnitArray = @[ @"角", @"分" ];
    
    NSString *upIntNum = [NSString string];
    NSString *upFloatNum = [NSString string];
    NSArray *numArray = [money componentsSeparatedByString:@"."];
    
    NSString *str1 = [numArray objectAtIndex:0];
    NSInteger num1 = str1.integerValue;
    for (int i = 0; i < intUnit.count && num1 > 0; i++) {//这一部分就是单纯的转化
        NSString *temp = @"";
        int tempNum = num1%10000;
        if (tempNum != 0 || i == 0) {
            for (int j = 0; j < measureArray.count && num1 > 0; j++) {
                temp = [NSString stringWithFormat:@"%@%@%@", [upperArray objectAtIndex:num1%10], [measureArray objectAtIndex:j],temp];//每次转化最后一位数
                num1 = num1/10;//数字除以10
            }
            upIntNum = [[temp stringByAppendingString:[intUnit objectAtIndex:i]] stringByAppendingString:upIntNum];
        } else {
            num1 /= 10000;
            temp = @"零";
            upIntNum = [temp stringByAppendingString:upIntNum];
        }
        
    }
    
    for (int m = 1; m < measureArray.count; m++) { //把零佰零仟这种情况转为零
        NSString *lingUnit = [@"零" stringByAppendingString:[measureArray objectAtIndex:m]];
        upIntNum = [upIntNum stringByReplacingOccurrencesOfString:lingUnit withString:@"零"];
    }
    
    while ([upIntNum rangeOfString:@"零零"].location != NSNotFound) {//多个零相邻的保留一个零
        upIntNum = [upIntNum stringByReplacingOccurrencesOfString:@"零零" withString:@"零"];
    }
    for (int k = 0; k < intUnit.count * 2; k++) { //零万、零亿这种情况转化为万零
        NSString *unit = [intUnit objectAtIndex:k%intUnit.count];
        NSString *lingUnit = [@"零" stringByAppendingString:unit];
        upIntNum = [upIntNum stringByReplacingOccurrencesOfString:lingUnit withString:[unit stringByAppendingString:@"零"]];
    }
    
    if (numArray.count == 2) {//小数部分转化
        NSString *floatStr = [numArray objectAtIndex:1];
        for (NSInteger i = floatStr.length; i > 0; i--) {
            NSString *temp = [floatStr substringWithRange:NSMakeRange(floatStr.length - i, 1)];
            NSInteger tempNum = temp.integerValue;
            if (tempNum == 0) continue;
            NSString *upNum = [upperArray objectAtIndex:tempNum];
            NSString *unit = [floatUnitArray objectAtIndex:floatStr.length - i];
            if (i < floatStr.length && upFloatNum.length == 0 && upIntNum.length > 0) {
                upFloatNum = @"零";
            }
            upFloatNum = [NSString stringWithFormat:@"%@%@%@", upFloatNum, upNum, unit];
        }
    }
    if (upFloatNum.length == 0) {
        upFloatNum = @"整";
    }
    
    NSString *amountInWords = [NSString stringWithFormat:@"%@%@", upIntNum, upFloatNum];
    
    while ([amountInWords rangeOfString:@"零零"].location != NSNotFound) {//再次除去多余的零
        amountInWords = [amountInWords stringByReplacingOccurrencesOfString:@"零零" withString:@"零"];
    }
    
    if ([amountInWords rangeOfString:@"零整"].location != NSNotFound) {
        amountInWords = [amountInWords stringByReplacingOccurrencesOfString:@"零整" withString:@"整"];
    }
    
    return amountInWords;
    
}

获取准确的手机内存

+ (float)freeDiskSpaceInBytes2
{
    if (@available(iOS 11.0, *)) {
        [NSURL alloc];
        NSURL * url = [[NSURL alloc]initFileURLWithPath:[NSString stringWithFormat:@"%@",NSHomeDirectory()]];
        NSError * error = nil;
        NSDictionary<NSURLResourceKey, id> * dict = [url resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
        if (error) {
            return 0;
        }
        float space = [dict[NSURLVolumeAvailableCapacityForImportantUsageKey] floatValue];
        return space;
    } else {
        NSError * error = nil;
        NSDictionary<NSFileAttributeKey, id> * systemAttributes =  [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
        if (error) {
            return 0;
        }
        float space = [systemAttributes[NSFileSystemFreeSize] floatValue];
        return space;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • 就在昨天,老妈和我微信视频,说:听说你买了一辆车。可不是吗?我终于买了一辆自行车。哈哈哈哈,两人不约大笑。 我买了...
    木木木侠阅读 950评论 0 4
  • 金灿灿的玉米囤满农家的庭院 红通通的小枣晾晒在屋前院后 黑黝黝的豆儿装好袋子聚在屋檐下 丰收!今年的秋,农家院落显...
    丰盈仓廪阅读 825评论 0 0
  • 寒风凛冽,寒气袭人,枯草萧疏,绿色尽失,今年的冬天如此苍白凄凉且冷漠. M点燃一支烟,吞云吐雾起来,一圈圈的烟雾,...
    幽谷泉涌阅读 846评论 0 1
  • 01 大熊和小琪是大学同学,也是我认识的人里,唯一一对毕业季在一起,结果谈了三年异地恋的恋人。 上周末,大熊还是失...
    子小洛阅读 3,794评论 47 61