系统弹窗:###
过期方法:
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];
定时器/延时:###
延迟调用方法一:
[self performSelector:@selector(nextQuestion:) withObject:nil afterDelay:2.0];
延迟调用方法二:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//需要调用的方法
});
定时器一:(精确度一般):
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(方法名) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:timer forMode:NSRunLoopCommonModes];
定时器二:(精确度高):
//1.创建CADisplayLink
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(方法名)];
//2.添加到运行循环
[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;
}
通知相关:###
发送通知
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相关:###
自动行高(需要配合autolayout自动布局)
self.tableView.estimatedRowHeight = 200; //预估行高
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相关:###
自定义layout的三个步骤(流水布局):
一、准备数据,并保存到布局对象数组
- (void)prepareLayout{
[super prepareLayout];
//准备item的数据
//定义数组用来保存每个item的frame
NSMutableArray* marr = [NSMutableArray array];
//给每个item布局
for (int i = 0; i < self.clothesInfos.count; i ++) {
//创建布局对象
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UICollectionViewLayoutAttributes* attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
//取出数据
ClothesModel* model = self.clothesInfos[i];
//计算frame
attr.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);
//保存数据
[marr addObject:attr];
}
//计算footView的frame
NSIndexPath* footPath = [NSIndexPath indexPathForRow:0 inSection:0];
UICollectionViewLayoutAttributes* footAtt = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter withIndexPath:footPath];
footAtt.frame = CGRectMake(footX, footY, footW, footH);
[marr addObject:footAtt];
// 把数据保存到布局数组
self.layoutAttributeMarr = marr;
}
二、计算内容区域
- (CGSize)collectionViewContentSize{
CGFloat CVCWidth = [UIScreen mainScreen].bounds.size.width;
UICollectionViewLayoutAttributes* lastAtt = self.layoutAttributeMarr.lastObject;
CGFloat CVCHeight = CGRectGetMaxY(lastAtt.frame)+_margin;//根据最大的Y值得到布局内容的高度
CGSize CVCSize = CGSizeMake(CVCWidth, CVCHeight);
return CVCSize;
}
三、返回布局对象数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
return self.layoutAttributeMarr;
}
数据存储方式:###
1.writeToFile
写入数据:
//1.1 你需要获取路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// .XXX 尾椎 只是决定 以哪中方式查看数据, 对存入的数据本身没有影响
NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"];
//1.2 写数据
NSArray *dataArray = @[@"亚洲国际舞王尼古拉斯赵四",@"小明",@"老王",@"霜霜"]; //1.3 存 //atomically 原子性的,数据安全的, 百分之九十九都是YES
[dataArray writeToFile:fiflePath atomically:YES];
读取数据:
//1.读取路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"];
//2.取出来
NSArray *dataArray = [NSArray arrayWithContentsOfFile:fiflePath];
2.userDefault(偏好设置)
写入数据:
//1. 获取系统的偏好设置对象
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//2. 存储数据
[defaults setObject:@"小明" forKey:@"name"];
[defaults setInteger:100 forKey:@"age"];
[defaults setBool:NO forKey:@"isTrue"];
//3.立即同步: 强制写入
[defaults synchronize];
读取数据:
//1.获取到偏好设置的路径
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//2.读取数据
NSString *name = [defaults objectForKey:@"name"];
NSInteger age = [defaults integerForKey:@"age"];
BOOL isTrue = [defaults boolForKey:@"isTrue"];
3.归档
写入数据:
//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];
读取数据:
*注意点: 如果使用归档 **
*1. 该对象必须遵守NSCoding 协议 编码协议 *
*2. 实现 encodeWithCoder方法 *
*3. 实现:initWIthCoder方法 *
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"];
//反归档 ,解档
CZPserson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
实现<NSCoding>协议方法:
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeBool:self.sex forKey:@"sex"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:self.name forKey:@"name"];
}
//反归档只是个过程, 告诉系统你读取的时候,想让别人读取哪些属性
- (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(旋转)
UIPanGestureRecognizer(拖动)
UIPinchGestureRecognizer(捏合,用于缩放)
//1.创建一个手势 并且监听
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
//最小触发 按压的时间
longPress.minimumPressDuration = 2.0;
//允许多大范围内 触发
longPress.allowableMovement = 20;
//2.添加到当前你想 操作的控件上
[self.myImageVIew addGestureRecognizer:longPress];
时间相关:###
获取当前时间:
1.获取当天的日期
NSDate *date = [NSDate date];
//2.获取当前日历
NSCalendar *lendar = [NSCalendar currentCalendar];
//3.从日历中获取 秒数
//(NSCalendarUnit) 单位
NSInteger second = [lendar component:NSCalendarUnitSecond fromDate:date];
2.抓取系统时间
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.基础动画:
//基础动画(缩放)
CABasicAnimation* basic1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
basic1.toValue = @(0.1);
//基础动画(旋转)
CABasicAnimation* basic2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
basic2.toValue = @(M_PI*2);
2.关键帧动画:
//创建路径
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.转场动画:
//3.添加转场动画
CATransition *sition = [CATransition animation];
//设置属性
//样式
sition.type = kCATransitionMoveIn;
//方向
sition.subtype = kCATransitionFromBottom;
//添加动画
[self.myImageView.layer addAnimation:sition forKey:nil];
4.组动画:
//创建路径
UIBezierPath* path = [UIBezierPath bezierPathWithArcCenter:self.view.center radius:150 startAngle:0 endAngle:M_PI*2 clockwise:YES];
//创建组动画
CAAnimationGroup* group = [CAAnimationGroup animation];
//创建动画1,关键帧动画
CAKeyframeAnimation* key = [CAKeyframeAnimation animationWithKeyPath:@"position"];
key.path = path.CGPath;
//创建动画2,基础动画(缩放)
CABasicAnimation* basic1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
basic1.toValue = @(0.1);
//创建动画3,基础动画(旋转)
CABasicAnimation* basic2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
basic2.toValue = @(M_PI*2);
//设置组动画
group.animations = @[key,basic1,basic2];
group.duration = 2.0;
group.repeatCount = 10;
[self.myLayer addAnimation:group forKey:nil];
NavigationController相关:###
设置导航栏外观
NSDictionary *dict = @{
NSFontAttributeName:[UIFont systemFontOfSize:16],
NSForegroundColorAttributeName:[UIColor whiteColor]
};
[self.navigationBar setTitleTextAttributes:dict];
// 修改导航栏上的item的外观
[self.navigationBar setTintColor:[UIColor whiteColor]];
跳转隐藏tabBar
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
// 1.隐藏tabbar
viewController.hidesBottomBarWhenPushed = YES;
// 2.调用父类方法执行跳转
[super pushViewController:viewController animated:YES];
}
设置状态栏
- (UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
加载本地的html###
// 创建一个url
// NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURL *url = [[NSBundle mainBundle] URLForResource:self.help.html withExtension:nil];
// 创建一个请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 使用webView加载请求对象
[webView loadRequest:request];
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(@"开始加载");}
// 加载结束时执行Javascript代码
- (void)webViewDidFinishLoad:(UIWebView *)webView{
// 需要执行的JavaScript代码
NSString *jsCode = [NSString stringWithFormat:@"window.location.href = '#%@'",self.help.ID];
// webView执行js代码
[webView stringByEvaluatingJavaScriptFromString:jsCode];
}
字符串转对象###
// 获取accessoryType
NSString *accessoryType = item[@"accessoryType"]; //UIImageView
// 根据字符串创建类
Class class = NSClassFromString(accessoryType);
// 根据类实例化对象
UIView *accessoryView = [[class alloc] init];
// 判断是否是UIImageView
if ([accessoryView isKindOfClass:[UIImageView class]]) {
// 强转成UIImageView
UIImageView *imgView = (UIImageView *)accessoryView;
// 设置ImgView的图片
imgView.image = [UIImage imageNamed:@"arrow_right"];
// 自适应大小
[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"]];
应用程序之间跳转###
NSURL *URL = [NSURL URLWithString:@"appB://ios.myapp.cn"];
[[UIApplication sharedApplication] openURL:URL];
裁剪图片###
//1.裁剪区域
CGRect rect = CGRectMake(x, y, w, h);
// 2.调用系统的裁剪方法裁剪图片
/* 参数: 1.被裁剪的大图 CG类型 2.需要裁剪的区域 */
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
// 转换成UIImage
UIImage *img = [UIImage imageWithCGImage:imageRef];
// 释放imageRef
CGImageRelease(imageRef);
传递事件,判断当前点是否在一个区域内###
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
// 1.描述一下按钮上部分的区域
CGRect rect = CGRectMake(0, 0, self.bounds.size.width, 100);
// 2.判断当前点击的点在不在上部分(如果不在,就直接返回nil)
if (!CGRectContainsPoint(rect, point)) {
return nil;
}
// 3.继续传递事件
return [super hitTest:point withEvent:event];
}
从网络获取图片###
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];
//设置名称
thread1.name = @"1111";
//设置优先级
thread1.threadPriority = 0.3;
[thread1s start];
第二种方法
[NSThread detachNewThreadSelector:@selector(buyTickets) toTarget:self withObject:nil];
第三种方法
[self performSelectorInBackground:@selector(buyTickets) withObject:nil];
url中文和特殊字符转码###
- (NSString *)generateUrl:(NSString *)url{
/** 第一个参数:NULL 第二个参数:C语言的字符串 第三个参数:NULL 第四个参数:要转义的字符串,不要乱转 第五个参数:编码 */
NSString *encodedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,(__bridge CFStringRef)url,NULL,CFSTR("+"),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return encodedString;
}
数据加密###
base64加密#####
加密
- (NSString *)base64Encode:(NSString *)originalString{
//1.将originalString转成二进制
NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding];
//2.需要将二进制转成Base64加密之后的字符串
return [data base64EncodedStringWithOptions:0];
}
解密
- (NSString *)base64Decode:(NSString *)base64String{
//1.Base64加密之后的字符串转成 NSData
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
//2.将二进制转在字符串
NSString *originalString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return originalString;
}
钥匙串#####
//设置钥匙串
self.bundleId = [NSBundle mainBundle].bundleIdentifier;
NSString* value = [SSKeychain passwordForService:self.bundleId account:@"password"];
//保存密码到钥匙串
[SSKeychain setPassword:password forService:self.bundleId account:@"password"];
MD5/SHA#####
//散列函数
- (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 散列函数
- (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 - 文件散列函数
#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 数组
* @param length 数组长度
*
* @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];
数组排序###
[marr sortUsingComparator:^NSComparisonResult(NewsModel* order1, NewsModel* order2) {
if ([order1.totalPrice floatValue] > [order2.totalPrice floatValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([order1.totalPrice floatValue] < [order2.totalPrice floatValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
数组倒序###
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];
}
字符串排序分组###
将字符串数组按照元素首字母顺序进行排序分组
+ (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];
//创建27个分组数组
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;
}
//去掉空数组
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; //设置最大可选择数
[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
// 色调 --> 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 ---> 环形卷积模糊(Available in iOS 9.0 and later)
// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置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设置尺寸(缩放图片)
- (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 ;
}
设置Label的行间距
+ (void)setLineSpaceWithString:(UILabel *)label{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
label.attributedText = attributedString;
}
设置Label里的字符有不同的颜色
//可根据自己的需求进行增删改
- (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];}
设置label显示多行文字
let lab = UILabel()
let title = "马上登陆\n\n开启我的奇妙之旅~"
//富文本单独设置后面的名称
let attr = NSMutableAttributedString(string: title)
//获取名字范围
let range = (title as NSString).rangeOfString("开启我的奇妙之旅~")
//单独设置制定范围的字符串
attr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(),NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range)
//赋值
lab.attributedText = attire
//设置换行
lab.numberOfLines = 0
//设置文字大小
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
* 联通号段: 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}$)";
/** * 中国联通: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;
}
}
常用函数:###
rand() ----随机数
abs() / labs() ----整数绝对值
fabs() / fabsf() / fabsl() ----浮点数绝对值
floor() / floorf() / floorl() ----向下取整
ceil() / ceilf() / ceill() ----向上取整
round() / roundf() / roundl() ----四舍五入
sqrt() / sqrtf() / sqrtl() ----求平方根
fmax() / fmaxf() / fmaxl() ----求最大值
fmin() / fminf() / fminl() ----求最小值
hypot() / hypotf() / hypotl() ----求直角三角形斜边的长度
fmod() / fmodf() / fmodl() ----求两数整除后的余数
modf() / modff() / modfl() ----浮点数分解为整数和小数
frexp() / frexpf() / frexpl() ----浮点数分解尾数和二为底的指数
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;
}
获取设备型号
+ (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;
}
缓存计算
//转换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];
}
}
KVO监听###
添加监听
addObserver(self.firstBtn, forKeyPath: "origin", options: [.New], context: nil)
接收监听
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print(self.firstBtn.frame.origin.y)
}
移除监听
deinit{
removeObserver(self, forKeyPath: "contentOffset")
}
截屏:
//获取当前Window 的截图
class func getScreenShoot() -> UIImage {
//获取当前window
let window = UIApplication.sharedApplication().keyWindow
//开启图片上下文
UIGraphicsBeginImageContext(window!.size)
//截取图片,渲染到图片上下文
window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: false)
//获取图片
let img = UIGraphicsGetImageFromCurrentImageContext()
//关闭图片上下文
UIGraphicsEndImageContext()
return img
}
本地文件读写###
创建NSURL的两种方式:
//必须加协议头(存在本地:file://)
1.[NSURL URLWithString:@"file:///Users/whitcast/Documents/1.txt"];
//不需要加协议头(系统帮你补上了file://)
2.[NSURL fileURLWithPath:@"/Users/whitcast/Documents/1.txt"];
通过url写入文件
NSString* str2= @"hello everyone";
NSURL *st = [NSURL fileURLWithPath:@"/Users/Cube/Desktop/ceshiw/ceshi123.txt"];
BOOL result = [str2 writeToURL:st atomically:YES encoding:NSUTF8StringEncoding error:nil];
通过url读取文件
NSString *str1 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];