iOS开发中常用的方法
生活随笔
收集整理的這篇文章主要介紹了
iOS开发中常用的方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
iOS開發(fā)中常用的方法
系統(tǒng)彈窗:
過期方法: UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"確認報價" message:@"報價不可修改" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil]; // 顯示出來 [alertView show]; 新方法: UIAlertController* alter = [UIAlertController alertControllerWithTitle:@"注銷賬戶" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction* action1 = [UIAlertAction actionWithTitle:@"確認退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {//填寫處理邏輯 }]; UIAlertAction* action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {//填寫處理邏輯 }]; [alter addAction:action1]; [alter addAction:action2]; //彈出選擇框 [self presentViewController:alter animated:YES completion:nil];定時器:
延遲調(diào)用方法一: [self performSelector:@selector(nextQuestion:) withObject:nil afterDelay:2.0]; 延遲調(diào)用方法二: dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //需要調(diào)用的方法 }); 定時器一:(精確度一般): NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(方法名) userInfo:nil repeats:YES]; NSRunLoop *runLoop = [NSRunLoop mainRunLoop]; [runLoop addTimer:timer forMode:NSRunLoopCommonModes]; 定時器二:(精確度高): //1.創(chuàng)建CADisplayLinkCADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(方法名)]; //2.添加到運行循環(huán)[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];計算控件尺寸:
- (CGSize)stringSize:(NSString *) string andMaxSize:(CGSize)maxSize andFontNum:(NSInteger)fontNum{ // 最大尺寸 NSDictionary *dict = @{NSFontAttributeName : [UIFont systemFontOfSize:fontNum] }; CGRect labelFrame = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil]; // 獲取 size并返回return labelFrame.size; }通知相關(guān):
發(fā)送通知NSNotificationCenter* center = [NSNotificationCenter defaultCenter];[center postNotificationName:@"OpenButtonNotification" object:nil userInfo:@{@"headerView":self}]; 接收通知NSNotificationCenter* center = [NSNotificationCenter defaultCenter];[center addObserver:self selector:@selector(方法名:) name::@"OpenButtonNotification" object:nil]; 注銷通知 -(void)dealloc{[[NSNotificationCenter defaultCenter] removeObserver:self]; }?TableView相關(guān):
自動行高(需要配合autolayout自動布局) self.tableView.estimatedRowHeight = 200; //預(yù)估行高 self.tableView.rowHeight = UITableViewAutomaticDimension;tableViewCell左滑功能 //tableView向左滑的功能 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ self.tableView.editing = !self.tableView.editing;ChangeInfosController* changeInfo = [[ChangeInfosController alloc]init]; [self.navigationController pushViewController:changeInfo animated:YES]; } //修改左滑的文字 -(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ return @"編輯"; } 取消重用 NSString*CellIdentifier = [NSStringstringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]]; //以indexPath來唯一確定cell FillOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell if (cell == nil) { cell = [[FillOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
CollectionView相關(guān):
自定義layout的三個步驟(流水布局): 一、準備數(shù)據(jù),并保存到布局對象數(shù)組 - (void)prepareLayout{ [super prepareLayout]; //準備item的數(shù)據(jù) //定義數(shù)組用來保存每個item的frameNSMutableArray* marr = [NSMutableArray array];//給每個item布局 for (int i = 0; i < self.clothesInfos.count; i ++) { //創(chuàng)建布局對象 NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0]; UICollectionViewLayoutAttributes* attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; //取出數(shù)據(jù) ClothesModel* model = self.clothesInfos[i];//計算frameattr.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);//保存數(shù)據(jù) [marr addObject:attr];}//計算footView的frameNSIndexPath* footPath = [NSIndexPath indexPathForRow:0 inSection:0]; UICollectionViewLayoutAttributes* footAtt = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter withIndexPath:footPath];footAtt.frame = CGRectMake(footX, footY, footW, footH);[marr addObject:footAtt]; // 把數(shù)據(jù)保存到布局數(shù)組 self.layoutAttributeMarr = marr; } 二、計算內(nèi)容區(qū)域 - (CGSize)collectionViewContentSize{ CGFloat CVCWidth = [UIScreen mainScreen].bounds.size.width; UICollectionViewLayoutAttributes* lastAtt = self.layoutAttributeMarr.lastObject; CGFloat CVCHeight = CGRectGetMaxY(lastAtt.frame)+_margin;//根據(jù)最大的Y值得到布局內(nèi)容的高度 CGSize CVCSize = CGSizeMake(CVCWidth, CVCHeight); return CVCSize; } 三、返回布局對象數(shù)組 - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { return self.layoutAttributeMarr; }數(shù)據(jù)存儲方式:
1.writeToFile 寫入數(shù)據(jù): //1.1 你需要獲取路徑NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // .XXX 尾椎 只是決定 以哪中方式查看數(shù)據(jù), 對存入的數(shù)據(jù)本身沒有影響 NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"]; //1.2 寫數(shù)據(jù)NSArray *dataArray = @[@"亞洲國際舞王尼古拉斯趙四",@"小明",@"老王",@"霜霜"];//1.3 存 //atomically 原子性的,數(shù)據(jù)安全的, 百分之九十九都是YES [dataArray writeToFile:fiflePath atomically:YES]; 讀取數(shù)據(jù): //1.讀取路徑 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"]; //2.取出來NSArray *dataArray = [NSArray arrayWithContentsOfFile:fiflePath]; 2.userDefault(偏好設(shè)置) 寫入數(shù)據(jù): //1. 獲取系統(tǒng)的偏好設(shè)置對象 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //2. 存儲數(shù)據(jù)[defaults setObject:@"小明" forKey:@"name"]; [defaults setInteger:100 forKey:@"age"]; [defaults setBool:NO forKey:@"isTrue"]; //3.立即同步: 強制寫入 [defaults synchronize]; 讀取數(shù)據(jù): //1.獲取到偏好設(shè)置的路徑 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //2.讀取數(shù)據(jù)NSString *name = [defaults objectForKey:@"name"];NSInteger age = [defaults integerForKey:@"age"];BOOL isTrue = [defaults boolForKey:@"isTrue"]; 3.歸檔 寫入數(shù)據(jù): //1.文件路徑 NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"]; //1. 有個對象CZPserson *p = [[CZPserson alloc]init];p.name = @"小明"; p.age = 100; p.sex = YES; //2.存儲 歸檔 [NSKeyedArchiver archiveRootObject:p toFile:filePath]; 讀取數(shù)據(jù): 注意點: 如果使用歸檔 * 1. 該對象必須遵守NSCoding 協(xié)議 編碼協(xié)議 2. 實現(xiàn) encodeWithCoder方法 3. 實現(xiàn):initWIthCoder方法NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"]; //反歸檔 ,解檔CZPserson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; 實現(xiàn)<NSCoding>協(xié)議方法: - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeBool:self.sex forKey:@"sex"]; [aCoder encodeInteger:self.age forKey:@"age"];[aCoder encodeObject:self.name forKey:@"name"]; } //反歸檔只是個過程, 告訴系統(tǒng)你讀取的時候,想讓別人讀取哪些屬性 - (instancetype)initWithCoder:(NSCoder *)aDecoder{if (self = [super init]) {self.name = [aDecoder decodeObjectForKey:@"name"];self.age = [aDecoder decodeIntegerForKey:@"age"];self.sex = [aDecoder decodeBoolForKey:@"sex"];} return self; }
隨機色:
- (UIColor *)randomColor{return [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
}
手勢識別:
UITapGestureRecognizer(點按) UILongPressGestureRecognizer(長按) UISwipeGestureRecognizer(輕掃) UIRotationGestureRecognizer(旋轉(zhuǎn)) UIPanGestureRecognizer(拖動) UIPinchGestureRecognizer(捏合,用于縮放) //1.創(chuàng)建一個手勢 并且監(jiān)聽 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)]; //最小觸發(fā) 按壓的時間 longPress.minimumPressDuration = 2.0; //允許多大范圍內(nèi) 觸發(fā) longPress.allowableMovement = 20; //2.添加到當前你想 操作的控件上 [self.myImageVIew addGestureRecognizer:longPress];時間相關(guān):
獲取當前時間: 1.獲取當天的日期NSDate *date = [NSDate date];//2.獲取當前日歷NSCalendar *lendar = [NSCalendar currentCalendar];//3.從日歷中獲取 秒數(shù)//(NSCalendarUnit) 單位NSInteger second = [lendar component:NSCalendarUnitSecond fromDate:date]; 2.抓取系統(tǒng)時間NSDate* nowDate = [NSDate date];NSDateFormatter* formatter = [[NSDateFormatter alloc]init];formatter.dateFormat = @"yyyy年MM月dd日HH時mm分ss秒";NSString *time = [formatter stringFromDate:nowDate]; 判斷當前時間 -(BOOL)isToday{ NSCalendar *calendar=[NSCalendar currentCalendar]; NSCalendarUnit unit=NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitDay; NSDateComponents *selfCmps=[calendar components:unit fromDate:self]; NSDateComponents *nowCmps=[calendar components:unit fromDate:[NSDate date]]; return selfCmps.year==nowCmps.year &&selfCmps.month==nowCmps.month &&selfCmps.day==nowCmps.day; } -(BOOL)isYesterday{ //生成只有年月日的日期對象 NSDateFormatter *fmt = [[NSDateFormatter alloc]init]; fmt.dateFormat=@"yyyy-MM-dd"; NSString *selfString =[fmt stringFromDate:self]; NSDate * selfDate=[fmt dateFromString:selfString]; NSString *nowString=[fmt stringFromDate:[NSDate date]]; NSDate *nowDate=[fmt dateFromString:nowString]; //比較差距 NSCalendar *calendar=[NSCalendar currentCalendar]; NSCalendarUnit unit=NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSDateComponents *cmps=[calendar components:unit fromDate:selfDate toDate:nowDate options:0]; return cmps.year==0 && cmps.month==0 && cmps.day==1 ; } -(BOOL)isTomorrow{ //生成只有年月日的日期對象 NSDateFormatter *fmr=[[NSDateFormatter alloc]init]; fmr.dateFormat=@"yyyy-MM-dd"; NSString *selfString=[fmr stringFromDate:self]; NSDate * selfDate=[fmr dateFromString:selfString]; NSString *nowString=[fmr stringFromDate:[NSDate date]]; NSDate *nowDate=[fmr dateFromString:nowString]; NSCalendar *calendar =[NSCalendar currentCalendar]; NSCalendarUnit unit=NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSDateComponents *cmps=[calendar components:unit fromDate:selfDate toDate:nowDate options:0]; return cmps.year==0 && cmps.month==0&& cmps.day==-1; } -(BOOL)isThisYeas{ NSCalendar *calendar=[NSCalendar currentCalendar]; NSInteger selfYear=[calendar component:NSCalendarUnitYear fromDate:self]; NSInteger nowYear=[calendar component:NSCalendarUnitYear fromDate:[NSDate date]]; return selfYear==nowYear; }動畫:
1.基礎(chǔ)動畫: //基礎(chǔ)動畫(縮放)CABasicAnimation* basic1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];basic1.toValue = @(0.1); //基礎(chǔ)動畫(旋轉(zhuǎn))CABasicAnimation* basic2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];basic2.toValue = @(M_PI*2); 2.關(guān)鍵幀動畫://創(chuàng)建路徑UIBezierPath* path = [UIBezierPath bezierPathWithArcCenter:self.view.center radius:150 startAngle:0 endAngle:M_PI*2 clockwise:YES];CAKeyframeAnimation* key = [CAKeyframeAnimation animationWithKeyPath:@"position"];key.path = path.CGPath; 3.轉(zhuǎn)場動畫: //3.添加轉(zhuǎn)場動畫CATransition *sition = [CATransition animation]; //設(shè)置屬性//樣式sition.type = kCATransitionMoveIn;//方向sition.subtype = kCATransitionFromBottom; //添加動畫 [self.myImageView.layer addAnimation:sition forKey:nil]; 4.組動畫: //創(chuàng)建路徑UIBezierPath* path = [UIBezierPath bezierPathWithArcCenter:self.view.center radius:150 startAngle:0 endAngle:M_PI*2 clockwise:YES]; //創(chuàng)建組動畫CAAnimationGroup* group = [CAAnimationGroup animation];//創(chuàng)建動畫1,關(guān)鍵幀動畫CAKeyframeAnimation* key = [CAKeyframeAnimation animationWithKeyPath:@"position"];key.path = path.CGPath;//創(chuàng)建動畫2,基礎(chǔ)動畫(縮放)CABasicAnimation* basic1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];basic1.toValue = @(0.1);//創(chuàng)建動畫3,基礎(chǔ)動畫(旋轉(zhuǎn))CABasicAnimation* basic2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];basic2.toValue = @(M_PI*2);//設(shè)置組動畫group.animations = @[key,basic1,basic2];group.duration = 2.0;group.repeatCount = 10;[self.myLayer addAnimation:group forKey:nil];NavigationController相關(guān):
設(shè)置導航欄外觀NSDictionary *dict = @{ NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor] }; [self.navigationBar setTitleTextAttributes:dict]; // 修改導航欄上的item的外觀 [self.navigationBar setTintColor:[UIColor whiteColor]]; 跳轉(zhuǎn)隱藏tabBar - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{ // 1.隱藏tabbar viewController.hidesBottomBarWhenPushed = YES; // 2.調(diào)用父類方法執(zhí)行跳轉(zhuǎn) [super pushViewController:viewController animated:YES]; } 設(shè)置狀態(tài)欄 - (UIStatusBarStyle)preferredStatusBarStyle{return UIStatusBarStyleLightContent; }加載本地的html:
// 創(chuàng)建一個url // NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"]; NSURL *url = [[NSBundle mainBundle] URLForResource:self.help.html withExtension:nil]; // 創(chuàng)建一個請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 使用webView加載請求對象 [webView loadRequest:request]; // 開始加載 - (void)webViewDidStartLoad:(UIWebView *)webView{ NSLog(@"開始加載");} // 加載結(jié)束時執(zhí)行Javascript代碼 - (void)webViewDidFinishLoad:(UIWebView *)webView{ // 需要執(zhí)行的JavaScript代碼 NSString *jsCode = [NSString stringWithFormat:@"window.location.href = '#%@'",self.help.ID]; // webView執(zhí)行js代碼 [webView stringByEvaluatingJavaScriptFromString:jsCode]; }字符串轉(zhuǎn)對象:
// 獲取accessoryType NSString *accessoryType = item[@"accessoryType"]; // 根據(jù)字符串創(chuàng)建類 Class class = NSClassFromString(accessoryType);// 根據(jù)類實例化對象 UIView *accessoryView = [[class alloc] init]; // 判斷是否是UIImageView if ([accessoryView isKindOfClass:[UIImageView class]]) { // 強轉(zhuǎn)成UIImageView UIImageView *imgView = (UIImageView *)accessoryView; // 設(shè)置ImgView的圖片 imgView.image = [UIImage imageNamed:@"arrow_right"]; // 自適應(yīng)大小[imgView sizeToFit];}
撥打電話:
//1.獲取APP 對象UIApplication *app = [UIApplication sharedApplication]; //2.打電話 NSURL *url = [NSURL URLWithString:@"tel://1234567890"]; [app openURL:url]; //簡寫: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://1234567890"]];應(yīng)用程序之間跳轉(zhuǎn):
NSURL *URL = [NSURL URLWithString:@"appB://ios.myapp.cn"]; [[UIApplication sharedApplication] openURL:URL];裁剪圖片
//1.裁剪區(qū)域 CGRect rect = CGRectMake(x, y, w, h); // 2.調(diào)用系統(tǒng)的裁剪方法裁剪圖片/* 參數(shù): 1.被裁剪的大圖 CG類型 2.需要裁剪的區(qū)域 */ CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect); // 轉(zhuǎn)換成UIImage UIImage *img = [UIImage imageWithCGImage:imageRef]; // 釋放imageRef CGImageRelease(imageRef);傳遞事件,判斷當前點是否在一個區(qū)域內(nèi)
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{// 1.描述一下按鈕上部分的區(qū)域 CGRect rect = CGRectMake(0, 0, self.bounds.size.width, 100); // 2.判斷當前點擊的點在不在上部分(如果不在,就直接返回nil) if (!CGRectContainsPoint(rect, point)) { return nil; } // 3.繼續(xù)傳遞事件 return [super hitTest:point withEvent:event]; }從網(wǎng)絡(luò)獲取圖片
NSURL* url = [NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/h%3D200/sign=c36bc6f3d32a28345ca6310b6bb4c92e/91ef76c6a7efce1b3e241e24a851f3deb58f65d5.jpg"];NSData* data = [NSData dataWithContentsOfURL:url];
UIImage* image = [UIImage imageWithData:data];
開啟子線程
第一種方法 NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(buyTickets) object:nil]; //設(shè)置名稱 thread1.name = @"1111"; //設(shè)置優(yōu)先級 thread1.threadPriority = 0.3; [thread1s start]; 第二種方法[NSThread detachNewThreadSelector:@selector(buyTickets) toTarget:self withObject:nil]; 第三種方法[self performSelectorInBackground:@selector(buyTickets) withObject:nil];url中文和特殊字符轉(zhuǎn)碼
- (NSString *)generateUrl:(NSString *)url{/** 第一個參數(shù):NULL 第二個參數(shù):C語言的字符串 第三個參數(shù):NULL 第四個參數(shù):要轉(zhuǎn)義的字符串,不要亂轉(zhuǎn) 第五個參數(shù):編碼 */
NSString *encodedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes( NULL,(__bridge CFStringRef)url,NULL,CFSTR("+"),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); return encodedString;
}
數(shù)據(jù)加密
base64加密 加密 - (NSString *)base64Encode:(NSString *)originalString{ //1.將originalString轉(zhuǎn)成二進制 NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding]; //2.需要將二進制轉(zhuǎn)成Base64加密之后的字符串 return [data base64EncodedStringWithOptions:0]; } 解密 - (NSString *)base64Decode:(NSString *)base64String{ //1.Base64加密之后的字符串轉(zhuǎn)成 NSData NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; //2.將二進制轉(zhuǎn)在字符串 NSString *originalString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return originalString; } 鑰匙串 //設(shè)置鑰匙串self.bundleId = [NSBundle mainBundle].bundleIdentifier;NSString* value = [SSKeychain passwordForService:self.bundleId account:@"password"]; //保存密碼到鑰匙串[SSKeychain setPassword:password forService:self.bundleId account:@"password"]; MD5/SHA //散列函數(shù) - (NSString *)md5String {const char *str = self.UTF8String;uint8_t buffer[CC_MD5_DIGEST_LENGTH];CC_MD5(str, (CC_LONG)strlen(str), buffer);return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)sha1String {const char *str = self.UTF8String;uint8_t buffer[CC_SHA1_DIGEST_LENGTH];CC_SHA1(str, (CC_LONG)strlen(str), buffer);return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)sha256String {const char *str = self.UTF8String;uint8_t buffer[CC_SHA256_DIGEST_LENGTH];CC_SHA256(str, (CC_LONG)strlen(str), buffer);return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)sha512String {const char *str = self.UTF8String;uint8_t buffer[CC_SHA512_DIGEST_LENGTH];CC_SHA512(str, (CC_LONG)strlen(str), buffer);return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - HMAC 散列函數(shù) - (NSString *)hmacMD5StringWithKey:(NSString *)key {const char *keyData = key.UTF8String;const char *strData = self.UTF8String;uint8_t buffer[CC_MD5_DIGEST_LENGTH];CCHmac(kCCHmacAlgMD5, keyData, strlen(keyData), strData, strlen(strData), buffer);return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)hmacSHA1StringWithKey:(NSString *)key {const char *keyData = key.UTF8String;const char *strData = self.UTF8String;uint8_t buffer[CC_SHA1_DIGEST_LENGTH];CCHmac(kCCHmacAlgSHA1, keyData, strlen(keyData), strData, strlen(strData), buffer);return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)hmacSHA256StringWithKey:(NSString *)key {const char *keyData = key.UTF8String;const char *strData = self.UTF8String;uint8_t buffer[CC_SHA256_DIGEST_LENGTH];CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer);return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)hmacSHA512StringWithKey:(NSString *)key {const char *keyData = key.UTF8String;const char *strData = self.UTF8String;uint8_t buffer[CC_SHA512_DIGEST_LENGTH];CCHmac(kCCHmacAlgSHA512, keyData, strlen(keyData), strData, strlen(strData), buffer);return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - 文件散列函數(shù) #define FileHashDefaultChunkSizeForReadingData 4096 - (NSString *)fileMD5Hash {NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];if (fp == nil) {return nil;}CC_MD5_CTX hashCtx;CC_MD5_Init(&hashCtx);while (YES) {@autoreleasepool {NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];CC_MD5_Update(&hashCtx, data.bytes, (CC_LONG)data.length);if (data.length == 0) {break;}}}[fp closeFile];uint8_t buffer[CC_MD5_DIGEST_LENGTH];CC_MD5_Final(buffer, &hashCtx);return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)fileSHA1Hash {NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];if (fp == nil) {return nil;}CC_SHA1_CTX hashCtx;CC_SHA1_Init(&hashCtx);while (YES) {@autoreleasepool {NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];CC_SHA1_Update(&hashCtx, data.bytes, (CC_LONG)data.length);if (data.length == 0) {break;}}}[fp closeFile];uint8_t buffer[CC_SHA1_DIGEST_LENGTH];CC_SHA1_Final(buffer, &hashCtx);return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)fileSHA256Hash {NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];if (fp == nil) {return nil;}CC_SHA256_CTX hashCtx;CC_SHA256_Init(&hashCtx);while (YES) {@autoreleasepool {NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];CC_SHA256_Update(&hashCtx, data.bytes, (CC_LONG)data.length);if (data.length == 0) {break;}}}[fp closeFile];uint8_t buffer[CC_SHA256_DIGEST_LENGTH];CC_SHA256_Final(buffer, &hashCtx);return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)fileSHA512Hash {NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];if (fp == nil) {return nil;}CC_SHA512_CTX hashCtx;CC_SHA512_Init(&hashCtx);while (YES) {@autoreleasepool {NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];CC_SHA512_Update(&hashCtx, data.bytes, (CC_LONG)data.length);if (data.length == 0) {break;}}}[fp closeFile];uint8_t buffer[CC_SHA512_DIGEST_LENGTH];CC_SHA512_Final(buffer, &hashCtx);return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - 助手方法 /** * 返回二進制 Bytes 流的字符串表示形式 * * @param bytes 二進制 Bytes 數(shù)組 * @param length 數(shù)組長度 * * @return 字符串表示形式 */ - (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length {NSMutableString *strM = [NSMutableString string];for (int i = 0; i < length; i++) {[strM appendFormat:@"%02x", bytes[i]];}return [strM copy]; }解壓縮文件
//下載完畢解壓到當前文件夾[SSZipArchive unzipFileAtPath:location.path toDestination:self.destinationPath uniqueId:nil];數(shù)組排序
[marr sortUsingComparator:^NSComparisonResult(NewsModel* model1, NewsModel* model2) { return [model1.num compare: model2.num]; }];數(shù)組倒序
NSArray* arr = [[ordersMarr reverseObjectEnumerator] allObjects];NSArray 快速求總和、最大值、最小值、平均值
- (void)caculateArray:(NSArray *)array{ CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];NSLog(@"%fn%fn%fn%f",sum,avg,max,min); return [NSString stringWithFormat:@"%f",sum];}
字符串排序分組
將字符串數(shù)組按照元素首字母順序進行排序分組 + (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{ if (array.count == 0){ return nil; } for (id obj in array) { if (![obj isKindOfClass:[NSString class]]){ return nil; } } UILocalizedIndexedCollation *indexedCollation = [UILocalizedInd exedCollation currentCollation]; NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count]; //創(chuàng)建27個分組數(shù)組 for (int i = 0; i < indexedCollation.sectionTitles.count; i++) { NSMutableArray *obj = [NSMutableArray array]; [objects addObject:obj]; } NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count]; //按字母順序進行分組 NSInteger lastIndex = -1; for (int i = 0; i < array.count; i++) { NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)]; [[objects objectAtIndex:index] addObject:array[i]]; lastIndex = index; } //去掉空數(shù)組 for (int i = 0; i < objects.count; i++) { NSMutableArray *obj = objects[i]; if (obj.count == 0) { [objects removeObject:obj]; } } //獲取索引字母 for (NSMutableArray *obj in objects) { NSString *str = obj[0]; NSString *key = [self firstCharacterWithString:str]; [keys addObject:key]; } NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [dic setObject:objects forKey:keys]; return dic; }計算磁盤大小
1.磁盤總空間大小 + (CGFloat)diskOfAllSizeMBytes{ CGFloat size = 0.0; NSError *error; NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) {#ifdef DEBUG NSLog(@"error: %@", error.localizedDescription);#endif }else{ NSNumber *number = [dic objectForKey:NSFileSystemSize]; size = [number floatValue]/1024/1024; } return size; } 2.磁盤可用空間大小 + (CGFloat)diskOfFreeSizeMBytes{ CGFloat size = 0.0; NSError *error; NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) {#ifdef DEBUG NSLog(@"error: %@", error.localizedDescription);#endif }else{ NSNumber *number = [dic objectForKey:NSFileSystemFreeSize]; size = [number floatValue]/1024/1024; } return size; }相冊選擇多文件(ZLPhotos)
//進入相冊 ZLPhotoPickerViewController* imgPickerController = [[ZLPhotoPickerViewController alloc]init]; imgPickerController.status = PickerViewShowStatusSavePhotos; imgPickerController.maxCount = 3; //設(shè)置最大可選擇數(shù) [self presentViewController:imgPickerController animated:YES completion:nil]; //block傳值 __weak typeof(self) weakSelf = self; imgPickerController.callBack = ^(NSArray *assets){ for (ZLPhotoAssets *photoAsset in assets) { UIImage *image = photoAsset.originImage; NSData *imageData =UIImagePNGRepresentation(image); //隨機生成的文件名稱 NSString *fileName = [NSString stringWithFormat:@"%d.png",arc4random_uniform(100)];//將每次獲取到的圖片,加入到字典中 [weakSelf.fileDict setObject:imageData forKey:fileName];} };
圖片處理
對圖片進行濾鏡處理 // 懷舊 --> CIPhotoEffectInstant 單色 --> CIPhotoEffectMono // 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade // 色調(diào) --> CIPhotoEffectTonal 沖印 --> CIPhotoEffectProcess // 歲月 --> CIPhotoEffectTransfer 鉻黃 --> CIPhotoEffectChrome // CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField + (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{ CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage = [[CIImage alloc] initWithImage:image]; CIFilter *filter = [CIFilter filterWithName:name]; [filter setValue:inputImage forKey:kCIInputImageKey]; CIImage *result = [filter valueForKey:kCIOutputImageKey]; CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return resultImage; } 對圖片進行模糊處理 // CIGaussianBlur ---> 高斯模糊 // CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later) // CIDiscBlur ---> 環(huán)形卷積模糊(Available in iOS 9.0 and later) // CIMedianFilter ---> 中值模糊, 用于消除圖像噪點, 無需設(shè)置radius(Available in iOS 9.0 and later) // CIMotionBlur ---> 運動模糊, 用于模擬相機移動拍攝時的掃尾效果(Available in iOS 9.0 and later) + (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{ CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage = [[CIImage alloc] initWithImage:image]; CIFilter *filter; if (name.length != 0) { filter = [CIFilter filterWithName:name]; [filter setValue:inputImage forKey:kCIInputImageKey]; if (![name isEqualToString:@"CIMedianFilter"]) { [filter setValue:@(radius) forKey:@"inputRadius"]; } CIImage *result = [filter valueForKey:kCIOutputImageKey]; CGImageRef cgImage = [context createCGImage:result fromRect: [result extent]]; UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return resultImage; } else { return nil; } } 毛玻璃效果 //Avilable in iOS 8.0 and later + (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{ UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; effectView.frame = frame; return effectView; } 給image設(shè)置尺寸(縮放圖片) - (UIImage *)imageByScalingToSize:(CGSize)targetSize{ UIImage *sourceImage = self; UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) ==NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor < heightFactor) scaleFactor = widthFactor; else scaleFactor = heightFactor; scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; if (widthFactor < heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ; }設(shè)置Label的行間距
+ (void)setLineSpaceWithString:(UILabel *)label{ NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:3]; //調(diào)整行間距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])]; label.attributedText = attributedString; } 設(shè)置Label里的字符有不同的顏色 //可根據(jù)自己的需求進行增刪改 - (void)stringColorSet { NSString*string = @"如何使得Label里的字符有不同的顏色?"; NSRange range = [string rangeOfString: @"Label"]; NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc] initWithString: string]; [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor redColor]}range: range]; [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor greenColor]}range: NSMakeRange(0, range.location)]; [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor cyanColor]}range: NSMakeRange(range.location+ range.length, 5)]; UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0.0f, 100.0f, 320.0f, 100.0f)]; [label setText: string]; [label setAttributedText: attribute];} 設(shè)置label顯示多行文字 let lab = UILabel() let title = "馬上登陸\n\n開啟我的奇妙之旅~" //富文本單獨設(shè)置后面的名稱 let attr = NSMutableAttributedString(string: title) //獲取名字范圍 let range = (title as NSString).rangeOfString("開啟我的奇妙之旅~") //單獨設(shè)置制定范圍的字符串 attr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(),NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range) //賦值 lab.attributedText = attire //設(shè)置換行 lab.numberOfLines = 0 //設(shè)置文字大小 lab.font = UIFont.systemFontOfSize(14) //文字顏色 lab.textColor = UIColor.grayColor() //文字居中 lab.textAlignment = .Center信息驗證
判斷手機號碼格式是否正確,利用正則表達式驗證 + (BOOL)isMobileNumber:(NSString *)mobileNum{if (mobileNum.length != 11) {return NO;} /** * 手機號碼: * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9] * 移動號段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705 * 聯(lián)通號段: 130,131,132,155,156,185,186,145,176,1709 * 電信號段: 133,153,180,181,189,177,1700 * / NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$"; /** * 中國移動:China Mobile * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705 */ NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(^1705\d{7}$)"; /** * 中國聯(lián)通:China Unicom * 130,131,132,155,156,185,186,145,176,1709 */ NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\d{8}$)|(^1709\d{7}$)"; /** * 中國電信:China Telecom * 133,153,180,181,189,177,1700 */ NSString *CT = @"(^1(33|53|77|8[019])\d{8}$)|(^1700\d{7}$)"; NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE]; NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM]; NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU]; NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT]; if (([regextestmobile evaluateWithObject:mobileNum] == YES) || ([regextestcm evaluateWithObject:mobileNum] == YES) || ([regextestct evaluateWithObject:mobileNum] == YES) || ([regextestcu evaluateWithObject:mobileNum] == YES)){return YES;} else {return NO;} } 2. 判斷郵箱格式是否正確,利用正則表達式驗證 + (BOOL)isAvailableEmail:(NSString *)email{ NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; return [emailTest evaluateWithObject:email]; } 3. 判斷字符串中是否含有空格 + (BOOL)isHaveSpaceInString:(NSString *)string{ NSRange _range = [string rangeOfString:@" "]; if (_range.location != NSNotFound) {return YES;}else {return NO;} } 4. 判斷字符串中是否含有中文 + (BOOL)isHaveChineseInString:(NSString *)string{for(NSInteger i = 0; i < [string length]; i++){int a = [string characterAtIndex:i];if (a > 0x4e00 && a < 0x9fff) {return YES;}}return NO; } 判斷身份證格式 + (BOOL)checkIdentityCardNo:(NSString*)value {value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];NSInteger length =0;if (!value) {return NO;}else {length = value.length;if (length !=15 && length !=18) {return NO;}}// 省份代碼NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];NSString *valueStart2 = [value substringToIndex:2];BOOL areaFlag =NO;for (NSString *areaCode in areasArray) {if ([areaCode isEqualToString:valueStart2]) {areaFlag =YES;break;}}if (!areaFlag) {return false;}NSRegularExpression *regularExpression;NSUInteger numberofMatch;NSInteger year =0;switch (length) {case 15:year = [[value substringWithRange:NSMakeRange(6,2)] integerValue] +1900;if (year %4 ==0 || (year 0 ==0 && year %4 ==0)) {regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性}else {regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性 }numberofMatch = [regularExpression numberOfMatchesInString:value options:NSMatchingReportProgress range:NSMakeRange(0, value.length)];if(numberofMatch >0) {return YES;}else {return NO;}case 18:year = [value substringWithRange:NSMakeRange(6,4)].intValue;if (year %4 ==0 || (year 0 ==0 && year %4 ==0)) {regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性}else {regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性 }numberofMatch = [regularExpression numberOfMatchesInString:value options:NSMatchingReportProgress range:NSMakeRange(0, value.length)];if(numberofMatch >0) {int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;int Y = S ;NSString *M =@"F";NSString *JYM =@"10X98765432";M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判斷校驗位if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {return YES;// 檢測ID的校驗位}else {return NO;}}else {return NO;}default:return false;} }常用函數(shù):
rand() ----隨機數(shù) abs() / labs() ----整數(shù)絕對值 fabs() / fabsf() / fabsl() ----浮點數(shù)絕對值 floor() / floorf() / floorl() ----向下取整 ceil() / ceilf() / ceill() ----向上取整 round() / roundf() / roundl() ----四舍五入 sqrt() / sqrtf() / sqrtl() ----求平方根 fmax() / fmaxf() / fmaxl() ----求最大值 fmin() / fminf() / fminl() ----求最小值 hypot() / hypotf() / hypotl() ----求直角三角形斜邊的長度 fmod() / fmodf() / fmodl() ----求兩數(shù)整除后的余數(shù) modf() / modff() / modfl() ----浮點數(shù)分解為整數(shù)和小數(shù) frexp() / frexpf() / frexpl() ----浮點數(shù)分解尾數(shù)和二為底的指數(shù) sin() / sinf() / sinl() ----求正弦值 sinh() / sinhf() / sinhl() ----求雙曲正弦值 cos() / cosf() / cosl() ----求余弦值 cosh() / coshf() / coshl() ----求雙曲余弦值 tan() / tanf() / tanl() ----求正切值 tanh() / tanhf() / tanhl() ----求雙曲正切值 asin() / asinf() / asinl() ----求反正弦值 asinh() / asinhf() / asinhl() ----求反雙曲正弦值 acos() / acosf() / acosl() ----求反余弦值 acosh() / acoshf() / acoshl() ----求反雙曲余弦值 atan() / atanf() / atanl() ----求反正切值 atan2() / atan2f() / atan2l() ----求坐標值的反正切值 atanh() / atanhf() / atanhl() ----求反雙曲正切值判斷手勢方向:
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview]; if (translation.y>0) { // NSLog(@"----------下-----------"); }else if(translation.y<0){ // NSLog(@"----------上-----------"); }獲取路徑下文件大小
- (unsigned long long)fileSizes{ // 獲得文件管理者 NSFileManager *mgr = [NSFileManager defaultManager]; // 是否為文件夾 BOOL isDirectory = NO; // 先判斷路徑的存在性 BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory];// 路徑不存在 if (!exists) return 0; // 如果是文件夾 if (isDirectory) { // 文件總大小 unsigned long long fileSize = 0; // 遍歷所有文件 NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self]; for (NSString *subpath in enumerator) { // 完整的子路徑 NSString *fullSubpath = [self stringByAppendingPathComponent:subpath]; fileSize += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize; } return fileSize; } // 如果是文件 return [mgr attributesOfItemAtPath:self error:nil].fileSize; }獲取設(shè)備型號
+ (NSString *)platform{size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size); sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
free(machine);
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (GSM)";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (CDMA)";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6Plus GSM";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 GSM+CDMA";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s GSM";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus Global";
if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (GSM)";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (GSM)";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)";
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (GSM)";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini Retina (WiFi)";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini Retina (GSM)";
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
return platform; }
緩存處理
緩存路徑 #define CacheFilePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] 清空緩存 +(BOOL)CleanCacheFilePath{ //拿到path路徑的下一級目錄的子文件夾 NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:CacheFilePath error:nil]; NSString *filePath = nil; NSError *error = nil; for (NSString *subPath in subPathArr) { filePath = [CacheFilePath stringByAppendingPathComponent:subPath]; //刪除子文件夾 [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; if (error) { NSLog(@"%@",error); continue; } } return YES; } 緩存計算 //轉(zhuǎn)換B/KB/MB/GB +(NSString *)SetCacheSize:(unsigned long long)fileSize{ // 單位 double unit = 1000.0; // 標簽文字 NSString *fileSizeText = nil; if (fileSize >= pow(unit, 3)) { // fileSize >= 1GB fileSizeText = [NSString stringWithFormat:@"%.2fGB", fileSize / pow(unit, 3)]; } else if (fileSize >= pow(unit, 2)) { // fileSize >= 1MB fileSizeText = [NSString stringWithFormat:@"%.2fMB", fileSize / pow(unit, 2)]; } else if (fileSize >= unit) { // fileSize >= 1KB fileSizeText = [NSString stringWithFormat:@"%.2fKB", fileSize / unit]; } else { // fileSize < 1KB fileSizeText = [NSString stringWithFormat:@"%zdB", fileSize]; } return fileSizeText; }給TabBarController添加滑動切換
//添加滑動手勢 UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedRightButton:)];[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];[self.view addGestureRecognizer:swipeLeft];UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedLeftButton:)];[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];[self.view addGestureRecognizer:swipeRight];- (void) tappedRightButton:(id)sender{
NSUInteger selectedIndex = [self.tabBarController selectedIndex]; NSArray *aryViewController = self.tabBarController.viewControllers; if (selectedIndex < aryViewController.count - 1) {[self.tabBarController setSelectedIndex:selectedIndex + 1];} } - (void) tappedLeftButton:(id)sender{NSUInteger selectedIndex = [self.tabBarController selectedIndex];if (selectedIndex > 0) {[self.tabBarController setSelectedIndex:selectedIndex - 1];} }
?
強則戒驕逸,處安已備。弱則暗圖強,待機而動。總結(jié)
以上是生活随笔為你收集整理的iOS开发中常用的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 炸裂了!来了一波新年微信红包封面,抓紧领
- 下一篇: 【DirectX11】【学习笔记(10)