ios 日常記錄-不定時(shí)更新

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;// 默認(rèn)是YES

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

5.html字符串轉(zhuǎn)換成富文本

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

通過設(shè)置控件的字體大小來改變字的大小,位置要放在給控件賦值之后

6.計(jì)算文本高度

-(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.獲取點(diǎn)擊cell的indexpath

//獲取當(dāng)前點(diǎn)擊cell的row或者section
self.tableView.indexPathForSelectedRow.row
self.tableView.indexPathForSelectedRow.section

//獲取當(dāng)前點(diǎn)擊cell的indexpath
self.mainView.indexPathsForSelectedRows

8.設(shè)置label不同位置字體大小和顏色

//設(shè)置不同字體顏色
-(void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    //設(shè)置字號(hào)
    [str addAttribute:NSFontAttributeName value:font range:range];
    //設(shè)置文字顏色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    
    label.attributedText = str;
}

9.UITextView :?jiǎn)?dòng)時(shí)文字位置不從頂部開始

- (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.隱藏導(dǎo)航欄返回按鈕

隱藏
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.在控件內(nèi)部取消鍵盤第一響應(yīng)者

//在控件內(nèi)部取消鍵盤第一響應(yīng)者
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

14.獲取cell在相對(duì)視圖上的位置

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

15.解決導(dǎo)航欄照片虛化放大

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

16.點(diǎn)擊圖片放大,再次點(diǎn)擊縮小

/**
 * @brief 點(diǎn)擊圖片放大,再次點(diǎn)擊縮小
 * @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];
    
    //點(diǎn)擊圖片縮小的手勢(shì)
    
    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.判斷字符串時(shí)候含有鍵盤表情

//判斷字符串時(shí)候含有鍵盤表情
+ (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

{

 //如果已經(jīng)連接Xcode調(diào)試則不輸出到文件

 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"]; //每次啟動(dòng)后都保存一個(gè)新的日志文件中

 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 ]; // 異常發(fā)生時(shí)的調(diào)用棧

 NSMutableString* strSymbols = [ [ NSMutableString alloc ] init ]; //將調(diào)用棧拼成輸出日志的字符串

 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];

 //把錯(cuò)誤日志寫到文件中

 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];

 }

 //把錯(cuò)誤日志發(fā)送到郵箱

 // NSString *urlStr = [NSString stringWithFormat:@"[mailto://test@163.com?subject=bug](mailto:mailto://test@163.com?subject=bug)報(bào)告&body=感謝您的配合!<br><br><br>錯(cuò)誤詳情:<br>%@",crashString ];

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

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

}

//錢格式轉(zhuǎn)換
- (NSString *)getAmountInWords:(NSString *)money{
    if (money.length == 0) {
        return @"";
    }
    if (money.floatValue == 0) {
        return @"零圓整";
    }
    //大寫數(shù)字
    NSArray *upperArray = @[ @"零",@"壹",@"貳",@"叁",@"肆",@"伍",@"陸",@"柒",@"捌",@"玖" ];
    /** 整數(shù)部分的單位 */
    NSArray *measureArray = @[ @"", @"拾", @"佰", @"仟"];
    /** 整數(shù)部分的單位 */
    NSArray *intUnit = @[@"圓", @"萬", @"億"];
    /** 小數(shù)部分的單位 */
    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++) {//這一部分就是單純的轉(zhuǎn)化
        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];//每次轉(zhuǎn)化最后一位數(shù)
                num1 = num1/10;//數(shù)字除以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++) { //把零佰零仟這種情況轉(zhuǎn)為零
        NSString *lingUnit = [@"零" stringByAppendingString:[measureArray objectAtIndex:m]];
        upIntNum = [upIntNum stringByReplacingOccurrencesOfString:lingUnit withString:@"零"];
    }
    
    while ([upIntNum rangeOfString:@"零零"].location != NSNotFound) {//多個(gè)零相鄰的保留一個(gè)零
        upIntNum = [upIntNum stringByReplacingOccurrencesOfString:@"零零" withString:@"零"];
    }
    for (int k = 0; k < intUnit.count * 2; k++) { //零萬、零億這種情況轉(zhuǎn)化為萬零
        NSString *unit = [intUnit objectAtIndex:k%intUnit.count];
        NSString *lingUnit = [@"零" stringByAppendingString:unit];
        upIntNum = [upIntNum stringByReplacingOccurrencesOfString:lingUnit withString:[unit stringByAppendingString:@"零"]];
    }
    
    if (numArray.count == 2) {//小數(shù)部分轉(zhuǎn)化
        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;
    
}

獲取準(zhǔn)確的手機(jī)內(nèi)存

+ (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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 就在昨天,老媽和我微信視頻,說:聽說你買了一輛車??刹皇菃??我終于買了一輛自行車。哈哈哈哈,兩人不約大笑。 我買了...
    木木木俠閱讀 1,053評(píng)論 0 4
  • 金燦燦的玉米囤滿農(nóng)家的庭院 紅通通的小棗晾曬在屋前院后 黑黝黝的豆兒裝好袋子聚在屋檐下 豐收!今年的秋,農(nóng)家院落顯...
    豐盈倉(cāng)廩閱讀 926評(píng)論 0 0
  • 寒風(fēng)凜冽,寒氣襲人,枯草蕭疏,綠色盡失,今年的冬天如此蒼白凄涼且冷漠. M點(diǎn)燃一支煙,吞云吐霧起來,一圈圈的煙霧,...
    幽谷泉涌閱讀 971評(píng)論 0 1
  • 01 大熊和小琪是大學(xué)同學(xué),也是我認(rèn)識(shí)的人里,唯一一對(duì)畢業(yè)季在一起,結(jié)果談了三年異地戀的戀人。 上周末,大熊還是失...
    子小洛閱讀 4,008評(píng)論 47 61

友情鏈接更多精彩內(nèi)容