po [[self view]recursiveDescription]
* 当视图第一次显示的时候会被调用 * 当这个视图显示到屏幕上了,点击按钮 * 添加子视图也会调用这个方法 * 当本视图的大小发生改变的时候是会调用的 * 当子视图的frame发生改变的时候是会调用的 * 当删除子视图的时候是会调用的
// 定义一个特殊字符的集合 NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: @"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""]; // 过滤字符串的特殊字符 NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
//平移按钮 CGAffineTransform transForm = self.buttonView.transform; self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0); //旋转按钮 CGAffineTransform transForm = self.buttonView.transform; self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4); //缩放按钮 self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2); //初始化复位 self.buttonView.transform = CGAffineTransformIdentity;
首先在viewDidLoad方法加入如下代码: if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; } if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) { [self.tableView setLayoutMargins:UIEdgeInsetsZero]; } 而后在重写willDisplayCell方法 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { [cell setSeparatorInset:UIEdgeInsetsZero]; } if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsZero]; } }
// 获取时间间隔 #define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); #define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
// 随机颜色 #define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1] // 颜色(RGB) #define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1] // 利用这种方法设置颜色和透明值,可不影响子视图背景色 #define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil] show]
- (void)exitApplication { AppDelegate *app = [UIApplication sharedApplication].delegate; UIWindow *window = app.window; [UIView animateWithDuration:1.0f animations:^{ window.alpha = 0; } completion:^(BOOL finished) { exit(0); }]; }
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil]; 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(@"%f\n%f\n%f\n%f",sum,avg,max,min);
- (void)touchesEnded:(NSSet<UITouch> *)touches withEvent:(UIEvent *)event { [self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]]; } - (void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color { // string为总体字符串, editStr为须要修改的字符串 NSRange range = [string rangeOfString:editStr]; NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string]; // 设置属性修改字体颜色UIColor与大小UIFont [attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range]; self.label.attributedText = attribute; }
#import<AVFoundation> // 1.获取音效资源的路径 NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"]; // 2.将路劲转化为url NSURL *tempUrl = [NSURL fileURLWithPath:path]; // 3.用转化成的url建立一个播放器 NSError *error = nil; AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error]; self.player = play; // 4.播放 [play play];
- (BOOL)isIpadPro { UIScreen *Screen = [UIScreen mainScreen]; CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale; CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale; BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad; BOOL hasIPadProWidth = fabs(width - 1024.f) < DBL xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed>> ~/.lldbinit echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit 下次从新运行项目,而后就不报错了。
-(void)test{ NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:3]; //调整行间距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.contentLabel.text length])]; self.contentLabel.attributedText = attributedString; }
@"UIViewContentModeScaleToFill", // 拉伸自适应填满整个视图 @"UIViewContentModeScaleAspectFit", // 自适应比例大小显示 @"UIViewContentModeScaleAspectFill", // 原始大小显示 @"UIViewContentModeRedraw", // 尺寸改变时重绘 @"UIViewContentModeCenter", // 中间 @"UIViewContentModeTop", // 顶部 @"UIViewContentModeBottom", // 底部 @"UIViewContentModeLeft", // 中间贴左 @"UIViewContentModeRight", // 中间贴右 @"UIViewContentModeTopLeft", // 贴左上 @"UIViewContentModeTopRight", // 贴右上 @"UIViewContentModeBottomLeft", // 贴左下 @"UIViewContentModeBottomRight", // 贴右下
#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); }; // 宏定义以前的用法 if (completionBlock) { completionBlock(arg1, arg2); } // 宏定义以后的用法 BLOCK_EXEC(completionBlock, arg1, arg2);
// 有时候咱们在xcode中打印中文,会打印出Unicode编码,还须要本身去一些在线网站转换,有了插件就方便多了。 DXXcodeConsoleUnicodePlugin 插件
[[UIApplication sharedApplication] setStatusBarHidden:NO]; [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
// 可自动生成模型的代码,省去写模型代码的时间 ESJsonFormat-for-Xcode
轻击手势(TapGestureRecognizer) 轻扫手势(SwipeGestureRecognizer) 长按手势(LongPressGestureRecognizer) 拖动手势(PanGestureRecognizer) 捏合手势(PinchGestureRecognizer) 旋转手势(RotationGestureRecognizer)
模拟器的位置: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs 文档安装位置: /Applications/Xcode.app/Contents/Developer/Documentation/DocSets 插件保存路径: ~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins 自定义代码段的保存路径: ~/Library/Developer/Xcode/UserData/CodeSnippets/ 若是找不到CodeSnippets文件夹,能够本身新建一个CodeSnippets文件夹。 证书路径 ~/Library/MobileDevice/Provisioning Profiles
获取家目录路径的函数 NSString *homeDir = NSHomeDirectory(); 获取Documents目录路径的方法 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [paths objectAtIndex:0]; 获取Documents目录路径的方法 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDir = [paths objectAtIndex:0]; 获取tmp目录路径的方法: NSString *tmpDir = NSTemporaryDirectory();
去除全部的空格 [str stringByReplacingOccurrencesOfString:@" " withString:@""] 去除首尾的空格 [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - (NSString *)uppercaseString; 所有字符转为大写字母 - (NSString *)lowercaseString 所有字符转为小写字母
pod install --verbose --no-repo-update pod update --verbose --no-repo-update 若是不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数能够省略这一步,而后速度就会提高很多。
在XCode中targets的build phases选项下Compile Sources下选择 不须要arc编译的文件 双击输入 -fno-objc-arc 便可 MRC工程中也可使用ARC的类,方法以下: 在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件 双击输入 -fobjc-arc 便可
_mTableView.tintColor = [UIColor redColor];
tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);
navigationController.hidesBarsOnSwipe = Yes
IQKeyboardManager https://github.com/hackiftekhar/IQKeyboardManager
图形上下是一个CGContextRef类型的数据。 图形上下文包含: 1,绘图路径(各类各样图形) 2,绘图状态(颜色,线宽,样式,旋转,缩放,平移) 3,输出目标(绘制到什么地方去?UIView、图片) 1,获取当前图形上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); 2,添加线条 CGContextMoveToPoint(ctx, 20, 20); 3,渲染 CGContextStrokePath(ctx); CGContextFillPath(ctx); 4,关闭路径 CGContextClosePath(ctx); 5,画矩形 CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120)); 6,设置线条颜色 [[UIColor redColor] setStroke]; 7, 设置线条宽度 CGContextSetLineWidth(ctx, 20); 8,设置头尾样式 CGContextSetLineCap(ctx, kCGLineCapSquare); 9,设置转折点样式 CGContextSetLineJoin(ctx, kCGLineJoinBevel); 10,画圆 CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100)); 11,指定圆心 CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1); 12,获取图片上下文 UIGraphicsGetImageFromCurrentImageContext(); 13,保存图形上下文 CGContextSaveGState(ctx) 14,恢复图形上下文 CGContextRestoreGState(ctx)
// 1. 开启一个与图片相关的图形上下文 UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0); // 2. 获取当前图形上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 3. 获取须要截取的view的layer [self.view.layer renderInContext:ctx]; // 4. 从当前上下文中获取图片 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); // 5. 关闭图形上下文 UIGraphicsEndImageContext(); // 6. 把图片保存到相册 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
第二种写法javascript
/** *截图功能 */ -(void)screenShot{ CGRect rect = self.view.frame; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [self.view.layer renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); i = [[UIImageView alloc]initWithFrame:CGRectMake(20, 70, 300, 500)]; i.layer.borderColor = [UIColor redColor].CGColor; i.layer.borderWidth = 2; i.image = img; [self.view addSubview:i]; i.userInteractionEnabled = YES; //tap手势 UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(event:)]; [i addGestureRecognizer:tapGesture]; [tapGesture setNumberOfTapsRequired:1]; }
//Swift UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default) //OC [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
-(void)viewDidLayoutSubviews{ if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)]; } if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) { [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)]; } } -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { [cell setSeparatorInset:UIEdgeInsetsZero]; } if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsZero]; } }
//1.当咱们的手离开屏幕时候隐藏 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { if(velocity.y > 0) { [self.navigationController setNavigationBarHidden:YES animated:YES]; } else { [self.navigationController setNavigationBarHidden:NO animated:YES]; } } velocity.y这个量,在上滑和下滑时,变化极小(小数),可是由于方向不一样,有正负之分,这就很好处理了。
//2.在滑动过程当中隐藏 //像safari (1) self.navigationController.hidesBarsOnSwipe = YES; (2) - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetY = scrollView.contentOffset.y + __tableView.contentInset.top; CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.tableView].y; if (offsetY > 64) { if (panTranslationY > 0) { //下滑趋势,显示 [self.navigationController setNavigationBarHidden:NO animated:YES]; } else { //上滑趋势,隐藏 [self.navigationController setNavigationBarHidden:YES animated:YES]; } } else { [self.navigationController setNavigationBarHidden:NO animated:YES]; } } 这里的offsetY > 64只是为了在视图滑过navigationBar的高度以后才开始处理,防止影响展现效果。panTranslationY是scrollView的pan手势的手指位置的y值,可能不是太好,由于panTranslationY这个值在较小幅度上下滑动时,可能都为正或都为负,这就使得这一方式不太灵敏.
效果图php
1第一种方式css
//方法一:设置透明度 [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.1]; //方法二:设置背景图片 /** * 设置导航栏,使其透明 * */ - (void)setNavigationBarColor:(UIColor *)color targetController:(UIViewController *)targetViewController{ //导航条的颜色 以及隐藏导航条的颜色targetViewController.navigationController.navigationBar.shadowImage = [[UIImage alloc]init]; 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(); [targetViewController.navigationController.navigationBar setBackgroundImage:theImage forBarMetrics:UIBarMetricsDefault]; }
二、设置透明导航栏html
当即投资BG为默认的导航栏 背景图片 java
透明navbarBG 是一张纯透明的png 图片python
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self createNav]; } - (void)createNav { //替换导航栏透明 UINavigationBar *navigationBar = self.navigationController.navigationBar; [navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName :[UIColor whiteColor] }]; //navigationBar.alpha = 0; [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsDefault]; [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsCompact]; //去黑线 [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault]; [navigationBar setShadowImage:[UIImage new]]; } //退出页面时候 恢复不透明 -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"当即投资BG"] forBarMetrics:UIBarMetricsDefault]; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"当即投资BG"] forBarMetrics:UIBarMetricsCompact]; } // 当滚动视图滚动到最顶端后,执行该方法 //向上滚动时候不透明 - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ // NSLog(@"scrollViewDidScroll"); CGPoint point=scrollView.contentOffset; if(point.y>5){ [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"当即投资BG"] forBarMetrics:UIBarMetricsDefault]; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"当即投资BG"] forBarMetrics:UIBarMetricsCompact]; self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:243/255.0 green:90.0/255.0 blue:3.0/255.0 alpha:1.0]; }else{ UINavigationBar *navigationBar = self.navigationController.navigationBar; [navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName :[UIColor whiteColor] }]; //navigationBar.alpha = 0; [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsDefault]; [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsCompact]; } // NSLog(@"%f,%f",point.x,point.y); // 从中能够读取contentOffset属性以肯定其滚动到的位置。 // 注意:当ContentSize属性小于Frame时,将不会出发滚动 }
//设置字体和行间距 UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)]; lable.text = @"你们好,我是Frank_chun,在这里咱们一块儿学习新的知识,总结咱们遇到的那些坑,共同的学习,共同的进步,共同的努力,只为美好的明天!!!有问题一块儿相互的探讨--438637472!!!"; lable.numberOfLines = 0; lable.font = [UIFont systemFontOfSize:12]; lable.backgroundColor = [UIColor grayColor]; [self.view addSubview:lable]; //设置每一个字体之间的间距 //NSKernAttributeName 这个对象所对应的值是一个NSNumber对象(包含小数),做用是修改默认字体之间的距离调整,值为0的话表示字距调整是禁用的; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}]; //设置某写字体的颜色 //NSForegroundColorAttributeName 设置字体颜色 NSRange blueRange = NSMakeRange([[str string] rangeOfString:@"Frank_chun"].location, [[str string] rangeOfString:@"Frank_chun"].length); [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange]; NSRange blueRange1 = NSMakeRange([[str string] rangeOfString:@"438637472"].location, [[str string] rangeOfString:@"438637472"].length); [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1]; //设置每行之间的间距 //NSParagraphStyleAttributeName 设置段落的样式 NSMutableParagraphStyle * par = [[NSMutableParagraphStyle alloc]init]; [par setLineSpacing:20]; //为某一范围内文字添加某个属性 //NSMakeRange表示所要的范围,从0到整个文本的长度 [str addAttribute:NSParagraphStyleAttributeName value:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];
效果图git
//第一种方法 //点击button倒计时 #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIButton * timeButton; @property (nonatomic, strong) NSTimer * timer; @property (nonatomic, strong)UIButton * btn; @end@implementation ViewController { NSInteger _time; } - (void)viewDidLoad { [super viewDidLoad]; _time = 5; self.btn = [UIButton buttonWithType:UIButtonTypeCustom]; _btn.backgroundColor = [UIColor orangeColor]; [_btn setTitle:@"获取验证码" forState:UIControlStateNormal]; _btn.titleLabel.font = [UIFont systemFontOfSize:15]; [_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside]; [self refreshButtonWidth]; [self.view addSubview:self.btn]; } - (void)refreshButtonWidth{ CGFloat width = 0; if (_btn.enabled){ width = 100; } else { width = 200; } _btn.center = CGPointMake(self.view.frame.size.width/2, 200); _btn.bounds = CGRectMake(0, 0, width, 40); //每次刷新,保证区域正确 [_btn setBackgroundImage:[self imageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal]; [_btn setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor] andSize:_btn.frame.size] forState:UIControlStateDisabled]; } - (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)aSize{ CGRect rect = CGRectMake(0.0f, 0.0f, aSize.width, aSize.height); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } - (void)btnAction:(UIButton *)sender{ sender.enabled = NO; [self refreshButtonWidth]; [sender setTitle:[NSString stringWithFormat:@"获取验证码(%zi)", _time] forState:UIControlStateNormal]; _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES]; } - (void)timeDown{ _time --; if (_time == 0) { [_btn setTitle:@"从新获取" forState:UIControlStateNormal]; _btn.enabled = YES; [self refreshButtonWidth]; [_timer invalidate]; _timer = nil; _time = 5 ; return; } [_btn setTitle:[NSString stringWithFormat:@"获取验证码(%zi)", _time] forState:UIControlStateNormal]; }
//第二种方法 #pragma mark -点击发送验证码 - (void)sendMessage:(UIButton *)btn{ if (self.phoneField.text.length == 0) { [self remindMessage:@"请输入正确的手机号"]; }else{ __block int timeout=60; //倒计时时间 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue); dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行 dispatch_source_set_event_handler(_timer, ^{ if(timeout<=0){ //倒计时结束,关闭 dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{ // 设置界面的按钮显示 根据本身需求设置 [btn setTitle:@"发送验证码" forState:UIControlStateNormal]; btn.userInteractionEnabled = YES; }); }else{ int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%d", seconds]; if ([strTime isEqualToString:@"0"]) { strTime = [NSString stringWithFormat:@"%d",60]; } dispatch_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据本身需求设置 //NSLog(@"____%@",strTime); [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1]; [btn setTitle:[NSString stringWithFormat:@"%@秒后从新发送",strTime] forState:UIControlStateNormal]; [UIView commitAnimations]; btn.userInteractionEnabled = NO; }); timeout--; } }); dispatch_resume(_timer); }
效果图github
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
[button setExclusiveTouch:YES];
UIImage* img=[UIImage imageNamed:@"2.png"];//原图 UIEdgeInsets edge=UIEdgeInsetsMake(0, 10, 0,10); //UIImageResizingModeStretch:拉伸模式,经过拉伸UIEdgeInsets指定的矩形区域来填充图片 //UIImageResizingModeTile:平铺模式,经过重复显示UIEdgeInsets指定的矩形区域来填充图 img= [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch]; self.imageView.image=img;
textField.placeholder = @"username is in here!"; [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
只能设置两种颜色,黑色和白色,系统默认黑色 设置为白色方法: (1)在plist里面添加Status bar style,值为UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色) (2)在Info.plist中设置UIViewControllerBasedStatusBarAppearance 为NO
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault]; self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
_pageControl.currentPageIndicatorTintColor=SFQRedColor; _pageControl.pageIndicatorTintColor=SFQGrayColor;
//有时候使用UITableView所实现的列表,会使用到section,可是又不但愿它粘在最顶上而是跟随滚动而消失或者出现 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (scrollView == _tableView) { CGFloat sectionHeaderHeight = 36; if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0); } else if (scrollView.contentOffset.y >= sectionHeaderHeight) { scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0); } } }
[UIView animateWithDuration:0.3 animations:^{ imageView.transform = CGAffineTransformMakeScale(2, 2); } completion:^(BOOL finished) { imageView.transform = CGAffineTransformMakeScale(1.0, 1.0); }];
//图片转字符串 -(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; }
-(BOOL)isChinese:(NSString *)str{ NSString *match=@"(^[\u4e00-\u9fa5]+$)"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match]; return [predicate evaluateWithObject:str]; }
-(NSString *)dateToString:(NSDate *)date { // 初始化时间格式控制器 NSDateFormatter *matter = [[NSDateFormatter alloc] init]; // 设置设计格式 [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"]; // 进行转换 NSString *dateStr = [matter stringFromDate:date]; return dateStr; } -(NSDate *)stringToDate:(NSString *)dateStr { // 初始化时间格式控制器 NSDateFormatter *matter = [[NSDateFormatter alloc] init]; // 设置设计格式 [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"]; // 进行转换 NSDate *date = [matter dateFromString:dateStr]; return date; }
imageview.userInteractionEnabled = YES; //tap手势 UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(event:)]; [imageview addGestureRecognizer:tapGesture]; [tapGesture setNumberOfTapsRequired:1]; - (void)event:(UITapGestureRecognizer *)gesture { NSLog(@"单击"); }
#pragma mark //获取请求链接的cookies [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(responseObject); NSDictionary *fields = [operation.response allHeaderFields]; //afnetworking写法 NSLog(@"fields = %@",[fields description]); // NSURL *url = [NSURL URLWithString:@"http://api.skyfox.org/api-test.php"]; NSURL *url = [NSURL URLWithString:urlStr]; //获取cookie方法1 NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:url]; NSLog(@"11--%@",cookies); //获取cookie方法2 //NSString *cookieString = [[HTTPResponse allHeaderFields] valueForKey:@"Set-Cookie"]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // NSLog(@"%@", error); if (fail) { fail(); } }];
imageView1 .transform=CGAffineTransformMakeRotation(M_PI_2);
#pragma mark //获取字符串须要的宽度 +(CGFloat)ZFYtextWidthFromTextString:(NSString *)text fontSize:(CGFloat)size{ CGSize size1 = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:size]}]; //返回计算出的行高 return size1.width; }
#pragma mark//获取字符串须要的高度 +(CGFloat)ZFYtextHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{ NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]}; CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil]; //返回计算出的行高 return rect.size.height; }
#pragma mark//Unicode转汉字 \u5f20\u4e09 → 张三 - (NSString *)replaceUnicode:(NSString *)unicodeStr { //张三 \u5f20\u4e09 NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"]; NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""]; NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding]; NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL]; // NSLog(@"Output = %@", returnStr); return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"]; } #pragma mark//汉字转 Unicode 张三 → \u5f20\u4e09 -(NSString *) utf8ToUnicode:(NSString *)string{ NSUInteger length = [string length]; NSMutableString *s = [NSMutableString stringWithCapacity:0]; for (int i = 0;i < length; i++){ unichar _char = [string characterAtIndex:i]; //判断是否为英文和数字 if (_char <= '9' && _char >='0'){ [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]]; }else if(_char >='a' && _char <= 'z'){ [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]]; }else if(_char >='A' && _char <= 'Z') { [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]]; }else{ [s appendFormat:@"\\u%x",[string characterAtIndex:i]]; } } return s; }
#pragma mark //获取相对时间 获取两个月前的时间 -2 为两个月前时间 2为两个月后时间 - (void)RelativeTime { NSDateComponents * components = [[NSDateComponents alloc] init]; components.month = -2; // components.day = 10; // components.hour = 10; NSCalendar * calendar = [NSCalendar currentCalendar]; NSDate * currentDate = [NSDate date]; NSDate * nextData = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly]; NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyy年MM月dd日HH时mm分ss秒"; NSString * str = [formatter stringFromDate:nextData]; NSLog(@"%@",str); }
#pragma mark 打印系统字体库 名字 NSArray *familyNames = [UIFont familyNames]; for( NSString *familyName in familyNames ) { printf( "Family: %s \n", [familyName UTF8String]); NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName]; for( NSString *fontName in fontNames ) { printf( "\tFont: %s \n", [fontName UTF8String] ); } }
//截取正方形的图片 centerBool为YES 表示从中心开始截取 +(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool{ /*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/ float imgWidth = image.size.width; float imgHeight = image.size.height; float viewWidth = mCGRect.size.width; float viewHidth = mCGRect.size.height; CGRect rect; if(centerBool) rect = CGRectMake((imgWidth-viewWidth)/2,(imgHeight-viewHidth)/2,viewWidth,viewHidth); else{ if(viewHidth<viewWidth) { if(imgWidth<= imgHeight) { rect=CGRectMake(0, 0,imgWidth, imgWidth*viewHidth/viewWidth); }else { float width = viewWidth*imgHeight/viewHidth; float x = (imgWidth - width)/2; if(x>0) { rect = CGRectMake(x,0, width, imgHeight); }else { rect = CGRectMake(0, 0, imgWidth, imgWidth*viewHidth/viewWidth); } } }else { if(imgWidth <= imgHeight) { float height = viewHidth*imgWidth/viewWidth; if(height< imgHeight) { rect =CGRectMake(0, 0, imgWidth, height); }else { rect = CGRectMake(0, 0,viewWidth*imgHeight/viewHidth, imgHeight); } }else { float width = viewWidth*imgHeight/viewHidth; if(width< imgWidth) { float x = (imgWidth - width)/2; rect =CGRectMake(x, 0,width, imgHeight); }else { rect =CGRectMake(0, 0,imgWidth, imgHeight); } } } } CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage,rect); CGRect smallBounds =CGRectMake(0, 0,CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef)); UIGraphicsBeginImageContext(smallBounds.size); CGContextRef context =UIGraphicsGetCurrentContext();CGContextDrawImage(context, smallBounds, subImageRef); UIImage *smallImage =[UIImage imageWithCGImage:subImageRef]; UIGraphicsEndImageContext(); return smallImage; }
//APPid就是上面的那串数字 NSString *urlStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",APPID]; NSURL *url = [NSURLURLWithString:urlStr]; [[UIApplicationsharedApplication]openURL:url];
#pragma mark -- //获取本地版本号 //获取本地版本号 NSString* thisVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
#pragma mark -- 获取appstore版本号 -(void)Postpath:(NSString *)path { NSString *url = [[NSString alloc] initWithFormat:@"http://itunes.apple.com/lookup?id=%@",@"414478124"]; NSURL *url = [NSURL URLWithString:path]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10]; [request setHTTPMethod:@"POST"]; NSOperationQueue *queue = [NSOperationQueue new]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){ NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init]; if (data) { NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) { [receiveStatusDic setValue:@"1" forKey:@"status"]; [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"] forKey:@"version"]; }else{ [receiveStatusDic setValue:@"-1" forKey:@"status"]; } }else{ [receiveStatusDic setValue:@"-1" forKey:@"status"]; } [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO]; }]; } -(void)receiveData:(id)sender { NSLog(@"receiveData=%@",sender); //打印获取到的版本号 }
//取消窗口第一响应 [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
//css 控制 <head><style>img{width:100%% !important;}</style></head> //js 控制 - (void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString: @"var script = document.createElement('script');" "script.type = 'text/javascript';" "script.text = /"function ResizeImages() { " "var myimg,oldwidth,oldheight;" "var maxwidth=320;"// 图片宽度 "for(i=0;i maxwidth){" "myimg.width = maxwidth;" "}" "}" "}/";" "document.getElementsByTagName('head')[0].appendChild(script);"]; [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"]; }
#pragma mark UITextField ----监听 [timesField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; // 监听事件 监听事件: // 监听改变按钮 - (void) textFieldDidChange:(UITextField*) textField { }
///设置push 以后返回按钮的 字体 UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init]; backbutton.title = @""; self.navigationItem.backBarButtonItem = backbutton;
life.navigationItem.hidesBackButton = YES;
- (void)webViewDidFinishLoad:(UIWebView *)aWebView { CGRect frame = aWebView.frame; frame.size.height = 1; aWebView.frame = frame; CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero]; frame.size = fittingSize; aWebView.frame = frame; NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height); }
#pragma mark //设置 阴影 [[self.calendarView layer] setShadowOffset:CGSizeMake(0, 0)]; [[self.calendarView layer] setShadowRadius:3]; [[self.calendarView layer] setShadowOpacity:0.4] ; [[self.calendarView layer] setShadowColor:[UIColor blackColor].CGColor];
#pragma mark 键盘监听 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil]; //注册键盘消失的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; - (void)keyboardWasShown:(NSNotification*)aNotification { //键盘高度 NSDictionary *userInfo = [aNotification userInfo]; //NSLog(@"%@",userInfo); NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; CGRect keyboardRect = [aValue CGRectValue]; NSInteger height = keyboardRect.size.height; CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]; } -(void)keyboardWillBeHidden:(NSNotification*)aNotification { }
#pragma mark //禁止微webview 上下拖动 UIWebView * d_intro = [[UIWebView alloc] init]; d_intro.delegate = self; d_intro.dataDetectorTypes = UIDataDetectorTypeLink; //取消右侧,下侧滚动条,去处上下滚动边界的黑色背景 d_intro.backgroundColor=[UIColor clearColor]; for (UIView *_aView in [d_intro subviews]) { if ([_aView isKindOfClass:[UIScrollView class]]) { [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO]; //右侧的滚动条 [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO]; //下侧的滚动条 for (UIView *_inScrollview in _aView.subviews) { if ([_inScrollview isKindOfClass:[UIImageView class]]) { _inScrollview.hidden = YES; //上下滚动出边界时的黑色的图片 } } } } [self.view addSubview:d_intro];
#pragma mark 图片保存沙盒 - (void)setHeadBgImage { BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; //NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"selfPhoto%d.jpg", [LoginManager sharedManager].userBasicInfo.uid]]; success = [fileManager fileExistsAtPath:imageFilePath]; UIImage *image1 = nil; if ([LoginManager sharedManager].loginSucess) { if (success) { NSData *data = [fileManager contentsAtPath:imageFilePath]; image1 = [UIImage imageWithData:data]; } }else{ image1 = [UIImage imageNamed:@"account_head_bg"]; } // NSLog(@"%@-%u",imageFilePath,success); [self setHeadBGImage:image1]; } - (void)saveImage:(UIImage *)image { BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"selfPhoto%d.jpg", [LoginManager sharedManager].userBasicInfo.uid]]; success = [fileManager fileExistsAtPath:imageFilePath]; if (success) { success = [fileManager removeItemAtPath:imageFilePath error:&error]; } BOOL result = [UIImagePNGRepresentation(image)writeToFile: imageFilePath atomically:YES]; // 保存成功会返回YES //UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(self.view.frame.size.width, 315)]; NSLog(@"%@-%u",imageFilePath,result); [self setHeadBGImage:image]; }
#pragma mark //旋转360 度 动画 -(void) startAnimation { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.01]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(endAnimation)]; _rechargeCover.transform = CGAffineTransformMakeRotation(angle * (M_PI / 180.0f)); NSLog(@"%f",angle * (M_PI / 180.0f)); [UIView commitAnimations]; } -(void)endAnimation { angle += 10; if (angle < 360) { [self startAnimation]; } }
#define DeviceMaxHeight ([UIScreen mainScreen].bounds.size.height) #define DeviceMaxWidth ([UIScreen mainScreen].bounds.size.width) #define widthRate DeviceMaxWidth/320 #define IOS8 ([[UIDevice currentDevice].systemVersion intValue] >= 8 ? YES : NO) // RGB颜色 #define UIColorFromRGB1(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
UIStoryboard *login = [UIStoryboard storyboardWithName:@"LoginModule" bundle:nil]; AlsNoticeController* alsNoticeController = [login instantiateViewControllerWithIdentifier:@"LoginVC"]; [self.navigationController pushViewController:alsNoticeController animated:YES];
#pragma mark //设置覆盖层视图 if (![[NSUserDefaults standardUserDefaults] boolForKey:@"guideFirst"]) { _guideCoverView =[[UIView alloc]initWithFrame:self.view.bounds]; _guideCoverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6]; UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow; [currentWindow addSubview:_guideCoverView]; }
#pragma mark 视图透明度 不影响子视图 alterView.backgroundColor=[[UIColor whiteColor] colorWithAlphaComponent:1];
#pragma mark 复制到系统剪切版 UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = self.label.text;
#pragma mark cocosPods指令 pod install --verbose --no-repo-update pod list 列出全部可用的第三方库 pod search query 搜包含query的第三方库 注意:这两个命令只搜存在于本地 /Users/yohunl/.cocoapods/ 下的文件 若是搜索网络的,能够先更新本地 pod repo update master,而后再搜索 pod lib create frameworkName 建立一个framework工程 pod lib lint 验证一个podspec文件是否有错误 podinstall --no-repo-update错误 这里的参数—no-repo-update,是告诉cocoapods不要更新repo.有么有感受每次pod install都很慢,那是由于每一次都会先更新本地的repo,加上此参数,就跳过了这个过程,将会很快 pod init 能够创建一个空的podfile 创建pod的spec文件 pod spec create spec名字 http://www.theonlylars.com/blog/2013/01/20/cocoapods-creating-a-pod-spec/ pod install 命令时会引起许多操做。要想深刻了解这个命令执行的详细内容,能够在这个命令后面加上 --verbose
90、背景图片按照某个像素拉伸web
self.messageImage.image = [[UIImage imageNamed:@"bbs_meaasge_frame"] stretchableImageWithLeftCapWidth:150 topCapHeight:20];