// 模糊效果
UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]; UIVisualEffectView *test = [[UIVisualEffectView alloc] initWithEffect:effect]; test.frame = self.view.bounds; test.alpha = 0; [self.view addSubview:test]; _mytext = test; UISlider *slidel = [[UISlider alloc]initWithFrame:CGRectMake(30, 300, 200, 20)]; slidel.backgroundColor = [UIColor purpleColor]; slidel.value = 0; slidel.maximumValue = 1.0; slidel.minimumValue = 0.0; [self.view addSubview:slidel]; slidel.enabled = YES; [slidel addTarget:self action:@selector(act:) forControlEvents:UIControlEventValueChanged]; - (void)act:(UISlider *)slider { _mytext.alpha = slider.value; }
// 隐藏手机的状态栏 -(BOOL)prefersStatusBarHidden { return YES; }
self.automaticallyAdjustsScrollViewInsets = YES; // 不让系统帮咱们把scrollView及其子类的视图向下调整64
//状态栏显示网络请求提示器 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; //将window显示在最外面. [[[[UIApplication sharedApplication] delegate] window] addSubview:self.view];
//cell高度 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *string = self.lrcArr[indexPath.row]; CGRect frame = [string boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName] context:nil]; return frame.size.height; }
// 在ARC工程中导入MRC的类 我们选中工程->选中targets中的工程,然后选中Build Phases->在导入的类后边加入标记 - fno-objc-arc // 在MRC工程中导入ARC的类 路径与上面一致,在该类后面加上标记 -fobjc-arc
//通过AV框架中的AVMakeRectWithAspectRatioInsideRect这个函数,可以将一个图片按比例凡在视图的中间,不需要计算: #import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)]; imageView.center = self.view.center; imageView.backgroundColor = [UIColor redColor]; imageView.contentMode = UIViewContentModeScaleToFill; UIImage *image = [UIImage imageNamed:@"1.jpg"]; imageView.image = image; CGRect iamgeAspectRect = AVMakeRectWithAspectRatioInsideRect(image.size, imageView.bounds); NSLog(@"iamgeAspectRect = %@, imageView =%@",NSStringFromCGRect(iamgeAspectRect),NSStringFromCGRect(imageView.frame)); [self.view addSubview:imageView]; }
上线之后自动关闭打印日志,节省资源 //NSLog #if DEBUG #define NSLog(FORMAT, ...) fprintf(stderr, "[%s:%d行] %s ",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]) #else #define NSLog(FORMAT, ...) nil #endif
动态加载高度 转而用WKWebView,监听estimatedProgress(WKWebView的加载进度)属性。 [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];添加监听。 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{ if (self.webView.estimatedProgress < 1.0){ return; } //完全加载后获取webview的高度 NSString *js = @"document.body.scrollHeight"; [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable height, NSError * _Nullable error) { NSLog(@"progress:%f height:%@",self.webView.estimatedProgress ,value); }]; }
TableView不显示没内容的Cell怎么办?
self.tableView.tableFooterView = [[UIView alloc] init];
改变自定义返回按钮的frame,代码如下: UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom]; [backButton setFrame:CGRectMake(-15, 0, 60, 30)]; [backButton setTitle:@"返回" forState:UIControlStateNormal]; [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [backButton setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal]; [backButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted]; [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside]; UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)]; [view addSubview:backButton]; UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:view]; self.navigationItem.leftBarButtonItem = item;
iOS 判断字符串是纯汉字还是含有汉字 新建一个字符串的类别: #import <Foundation/Foundation.h> @interface NSString (China) - (BOOL)isChinese;//判断是否是纯汉字 - (BOOL)includeChinese;//判断是否含有汉字 @end #import "NSString+China.h" @implementation NSString (China) -(BOOL)isChinese { NSString *match = @"(^[u4e00-u9fa5]+$)"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match]; return [predicate evaluateWithObject:self]; } -(BOOL)includeChinese { for(int i=0; i< [self length];i++) { int a =[self characterAtIndex:i]; if( a >0x4e00&& a <0x9fff){ return YES; } } return NO; } @end #import "ViewController.h" #import "NSString+China.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *string1 = @"Liuzhiwu 纯汉字"; if (string1.isChinese) { NSLog(@"纯汉字"); } else if (string1.includeChinese) { NSLog(@"包含汉字"); } else{ NSLog(@"纯字母"); } }
隐藏tabbar的坑:
我们有的时候需要隐藏和显示tabbar,但有的时候会出现黑色的条.是因为push的时候有动画的效果,可以使用下面的这种方法,也就是隐藏tabbar的另一种方法
[self.navigationController setNavigationBarHidden:YES animated:animated];
快速查找工程文件
工程大了,常常不记得哪个文件在哪个文件夹的子目录下,或者记得也得不厌其烦地层层打开,可以 cmd + shift + O组合键调出Open Quickly窗口,快速查找所需文件。
禁止锁屏: [UIApplication sharedApplication].idleTimerDisabled = YES; 或 [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
判断视图是不是指定视图的子视图
BOOL isView = [textView isDescendantOfView:self.view];
防止scrollView手势覆盖侧滑手势
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
改变导航栏的alpha -(void)scrollViewDidScroll:(UIScrollView *)scrollView { //第一种方法 // CGFloat offsetToShow = 200.0;//滑动多少就完全显示 // CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; // [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha; //第二种方法 CGFloat offsetToShow = 200.0; CGFloat alpha = (offsetToShow - scrollView.contentOffset.y) / offsetToShow - 1; [self.navigationController.navigationBar setShadowImage:[UIImage new]]; [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault]; } //生成一张纯色的图片 - (UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; }
获取硬盘总容量与可用容量: NSFileManager *fileManager = [NSFileManager defaultManager]; NSDictionary *attributes = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil]; NSLog(@"容量%.2fG",[attributes[NSFileSystemSize] doubleValue] / (powf(1024, 3))); NSLog(@"可用%.2fG",[attributes[NSFileSystemFreeSize] doubleValue] / powf(1024, 3));
//图片与字符串相互转换 -(NSString *)UIImageToBase64Str:(UIImage *) image { NSData *data = UIImageJPEGRepresentation(image, 1.0f); NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; return encodedImageStr; } //字符串转图片 -(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr { NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:_encodedImageStr]; UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData]; return _decodedImage; }
//根据Label文字,自适应高度 CGRect rect = [contentString boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:15]} context:nil] ;
@param CGSize 规定文本显示的最大范围
@param options 按照何种设置来计算范围
@param attributes 文本内容的一些属性,例如字体大小,字体类型等 (字体不一样,高度也不一样)
@parma context 上下文 可以规定一些其他的设置 但是一般都是nil
//导航栏渐变效果 -(void)scrollViewDidScroll:(UIScrollView *)scrollView { //第一种方法 // CGFloat offsetToShow = 200.0;//滑动多少就完全显示 // CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; // [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha; //第二种方法 CGFloat offsetToShow = 200.0; CGFloat alpha = (offsetToShow - scrollView.contentOffset.y) / offsetToShow - 1; [self.navigationController.navigationBar setShadowImage:[UIImage new]]; [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault]; } //生成一张纯色的图片 - (UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; }
//导航栏自动缩放效果 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetY = scrollView.contentOffset.y + scrollView.contentInset.top; CGFloat scale = 1.0; // 放大 if (offsetY < 0) { // 允许下拉放大的最大距离为300 // 1.5是放大的最大倍数,当达到最大时,大小为:1.5 * 70 = 105 // 这个值可以自由调整 scale = MIN(1.5, 1 - offsetY / 300); } else if (offsetY > 0) { // 缩小 // 允许向上超过导航条缩小的最大距离为300 // 为了防止缩小过度,给一个最小值为0.45,其中0.45 = 31.5 / 70.0,表示 // 头像最小是31.5像素 scale = MAX(0.45, 1 - offsetY / 300); } self.headerImageView.transform = CGAffineTransformMakeScale(scale, scale); // 保证缩放后y坐标不变 CGRect frame = self.headerImageView.frame; frame.origin.y = -self.headerImageView.layer.cornerRadius / 2; self.headerImageView.frame = frame; }
在使用SDWebImage加载较多图片造成内存警告时,定期调用 [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"]; 可解决。