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:@""];
        //去除空格  
        html = [html stringByReplacingOccurrencesOfString:@" " 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://[email protected]?subject=bug](mailto:mailto://[email protected]?subject=bug)报告&body=感谢您的配合!


错误详情:
%@",crashString ]; // NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; // [[UIApplication sharedApplication] openURL:url]; }

你可能感兴趣的:(ios 日常记录-不定时更新)