1.压缩图片
- #pragma mark 处理图片
- - (void)useImage:(UIImage *)image
- {
- NSLog(@"with-----%f heught-----%f",image.size.width,image.size.height);
- float scales = image.size.height / image.size.width; //图片比例
- NSLog(@"图片比例:%f",scales);
- UIImage * normalImg;
- if (image.size.width >300 || image.size.height > 300) {
- if (scales > 1) {
- normalImg = [self imageWithImageSimple:image scaledToSize:CGSizeMake(300 / scales, 300)];
- }else {
- normalImg = [self imageWithImageSimple:image scaledToSize:CGSizeMake(300 ,3300 * scales)];
- }
- }
- else {
- normalImg = image;
- }
- NSLog(@"第一次处理后:with-----%f height-----%f",normalImg.size.width, normalImg.size.height);
- CGSize newSize = CGSizeMake(normalImg.size.width, normalImg.size.height);
- float kk = 1.0f;//图片压缩系数
- int mm;//压缩后的大小
- float aa = 1.0f;//图片压缩系数变化步长(可变)
- mm = (int)UIImageJPEGRepresentation(normalImg, kk).length;
- while (mm / 1024 > 300) {
- if (kk > aa + aa / 10) {
- kk -= aa;
- if (mm == (int)UIImageJPEGRepresentation(normalImg, kk).length) {
- break;
- }
- mm = (int)UIImageJPEGRepresentation(normalImg, kk).length;
- }else{
- aa /= 10;
- }
- }
- NSLog(@"KK:%f -- aa:%f",kk,aa);
- #warning 图片压缩
- NSLog(@"第二次处理后:with-----%f height-----%f",normalImg.size.width, normalImg.size.height);
- NSData *newData;
- newData = UIImageJPEGRepresentation(normalImg, kk);//最后压缩结果
- if (newData.length/1024 > 300) {
- [APPRequest showAlert:@"提示" message:@"图片过大"];
- }else{
- // 上传图片网络请求
- }
- }];
- }
- }
2.发布时间
- NSDate * timeDate = [NSDate date];
- NSTimeInterval nowInt = [timeDate timeIntervalSince1970]*1;
- NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
- [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
- NSDate* publishDate = [dateformatter dateFromString:[demandlist.publish_time substringToIndex:19]];
- NSTimeInterval publishInt = [publishDate timeIntervalSince1970]*1;
- NSTimeInterval cha = nowInt - publishInt;
- NSString *timeString=@"";
- if (cha/3600<1) {
- timeString = [NSString stringWithFormat:@"%f", cha/60];
- timeString = [timeString substringToIndex:timeString.length-7];
- timeString = [NSString stringWithFormat:@"%@分钟前发布", timeString];
- }
- if (cha/3600>1&&cha/86400<1) {
- timeString = [NSString stringWithFormat:@"%f", cha/3600];
- timeString = [timeString substringToIndex:timeString.length-7];
- timeString = [NSString stringWithFormat:@"%@小时前发布", timeString];
- }
- if (cha/86400>1)
- {
- timeString = [NSString stringWithFormat:@"%f", cha/86400];
- timeString = [timeString substringToIndex:timeString.length-7];
- timeString = [NSString stringWithFormat:@"%@天前发布", timeString];
- }
3.返回字符串所占的尺寸
- //返回字符串所占用的尺寸.
- -(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
- { NSDictionary *attrs = @{NSFontAttributeName : font};
- return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
- }
4.tableView自动滑倒某一行
- NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:10 inSection:0];
- [[self tableView] scrollToRowAtIndexPath:scrollIndexPath
- atScrollPosition:UITableViewScrollPositionTop animated:YES];
5.tableView刷新某个分区或某行
- NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
- [tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
- //一个cell刷新
- NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
- [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone]; <span style="font-family: Arial, Helvetica, sans-serif;"> </span>
6.读取plist文件
- NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];
- NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
7.关键字高亮
- label.text = [NSString stringWithFormat:@" 视野头条:%@",home.title];
- NSString *str = [NSString stringWithFormat:@" 视野头条:%@",home.title];
- NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc]initWithString:str];
- NSRange range = [str rangeOfString:@"视野头条:"];
- [titleStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:range];
- [label setAttributedText:titleStr];
8.去掉字符串中的空格
- NSString *str = @"dhak d sh akdl ";
- NSString *strUrl = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
9.UIImage添加生成圆角图片的扩展API
- 给UIImage添加生成圆角图片的扩展API:
- - (UIImage *)imageWithCornerRadius:(CGFloat)radius {
- CGRect rect = (CGRect){0.f, 0.f, self.size};
- UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
- CGContextAddPath(UIGraphicsGetCurrentContext(),
- [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
- CGContextClip(UIGraphicsGetCurrentContext());
- [self drawInRect:rect];
- UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return image;
- }
- //然后调用时就直接传一个圆角来处理:
- imgView.image = [[UIImage imageNamed:@"test"] hyb_imageWithCornerRadius:4];
- //最直接的方法就是使用如下属性设置:
- imgView.layer.cornerRadius = 10;
- // 这一行代码是很消耗性能的
- imgView.clipsToBounds = YES;
- //
好处是使用简单,操作方便。坏处是离屏渲染(off-screen-rendering)需要消耗性能。对于图片比较多的视图上,不建议使用这种方法来设
置圆角。通常来说,计算机系统中CPU、GPU、显示器是协同工作的。CPU计算好显示内容提交到GPU,GPU渲染完成后将渲染结果放入帧缓冲区。 - //简单来说,离屏渲染,导致本该GPU干的活,结果交给了CPU来干,而CPU又不擅长GPU干的活,于是拖慢了UI层的FPS(数据帧率),并且离屏需要创建新的缓冲区和上下文切换,因此消耗较大的性能。
10.正则法则
- //1.验证邮箱
- + (BOOL)validateEmail:(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];
- }
- //2.验证手机(简单的)
- + (BOOL)validatePhone:(NSString *)phone
- {
- NSString *phoneRegex = @"1[3|5|7|8|][0-9]{9}";
- NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
- return [phoneTest evaluateWithObject:phone];
- }
- //验证手机(复杂的)
- + (BOOL)validatePhone:(NSString *)phone
- {
- /**
- * 手机号码
- * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
- * 联通:130,131,132,152,155,156,185,186
- * 电信:133,1349,153,180,189
- */
- NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
- /**
- 10 * 中国移动:China Mobile
- 11 * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
- 12 */
- NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
- /**
- 15 * 中国联通:China Unicom
- 16 * 130,131,132,152,155,156,185,186
- 17 */
- NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
- /**
- 20 * 中国电信:China Telecom
- 21 * 133,1349,153,180,189
- 22 */
- NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
- /**
- 25 * 大陆地区固话及小灵通
- 26 * 区号:010,020,021,022,023,024,025,027,028,029
- 27 * 号码:七位或八位
- 28 */
- // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
- 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:phone] == YES)
- || ([regextestcm evaluateWithObject:phone] == YES)
- || ([regextestct evaluateWithObject:phone] == YES)
- || ([regextestcu evaluateWithObject:phone] == YES))
- {
- if([regextestcm evaluateWithObject:phone] == YES) {
- NSLog(@"China Mobile");
- } else if([regextestct evaluateWithObject:phone] == YES) {
- NSLog(@"China Telecom");
- } else if ([regextestcu evaluateWithObject:phone] == YES) {
- NSLog(@"China Unicom");
- } else {
- NSLog(@"Unknow");
- }
- return YES;
- }
- else
- {
- return NO;
- }
- }
11.清除缓存
- // 删除缓存
- - (void)removeCache
- {
- NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
- NSLog(@"%@",cachePath);
- NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
- for (NSString *p in files) {
- NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
- if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
- [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
- }
- }
- }
- // 计算清除的缓存大小
- - (CGFloat)floatWithPath:(NSString *)path
- {
- CGFloat num = 0;
- NSFileManager *man = [NSFileManager defaultManager];
- if ([man fileExistsAtPath:path]) {
- NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
- NSString *fileName;
- while ((fileName = [childFile nextObject]) != nil) {
- NSString *fileSub = [path stringByAppendingPathComponent:fileName];
- num += [self fileSizeAtPath:fileSub];
- }
- }
- return num / (1024.0 * 1024.0);
- }
- //计算单个文件大小
- - (long long)fileSizeAtPath:(NSString *)file
- {
- NSFileManager *man = [NSFileManager defaultManager];
- if ([man fileExistsAtPath:file]) {
- return [[man attributesOfItemAtPath:file error:nil] fileSize];
- }
- return 0;
- }
12 系统原生态二维码扫描(包括闪光灯,系统提示音)
- #import <AVFoundation/AVFoundation.h>
- #import <AudioToolbox/AudioToolbox.h> // 系统提示音
- #define SCANVIEW_EdgeTop 40.0
- #define SCANVIEW_EdgeLeft 50.0
- #define TINTCOLOR_ALPHA 0.2 //浅色透明度
- #define DARKCOLOR_ALPHA 0.5 //深色透明度
- #define VIEW_WIDTH [UIScreen mainScreen].bounds.size.width
- #define VIEW_HEIGHT [UIScreen mainScreen].bounds.size.height
- /*
- *********注意 :系统原生态二维码扫描 苹果官方目前不支持扫扫描图册图片 ************
- 1.第一步 引入框架 AVFoundation.framework
- 2.第二步 声明代理:AVCaptureMetadataOutputObjectsDelegate 。 define 几个东东用来画框、画线:
- */
- @interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
- {
- AVCaptureSession * session;//输入输出的中间桥梁
- UIView *AVCapView;//此 view 用来放置扫描框、取消按钮、说明 label
- UIView *_QrCodeline;//上下移动绿色的线条
- NSTimer *_timer;
- }
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- [self createUI];
- // Do any additional setup after loading the view, typically from a nib.
- }
- #pragma mark 4.在某个方法中(我是点击扫描按钮)创建扫描界面,开始扫描
- - (void)createUI{
- //创建一个 view 来放置扫描区域、说明 label、取消按钮
- UIView *tempView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, [UIScreen mainScreen].bounds.size.height )];
- AVCapView = tempView;
- AVCapView.backgroundColor = [UIColor colorWithRed:54.f/255 green:53.f/255 blue:58.f/255 alpha:1];
- UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, [UIScreen mainScreen].bounds.size.height - 100, 50, 25)];
- UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 268, 290, 60)];
- label.numberOfLines = 0;
- label.text = @"小提示:将条形码或二维码对准上方区域中心即可";
- label.textColor = [UIColor grayColor];
- [cancelBtn setTitle:@"取消" forState: UIControlStateNormal];
- [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
- [cancelBtn addTarget:self action:@selector(touchAVCancelBtn) forControlEvents:UIControlEventTouchUpInside];
- [AVCapView addSubview:label];
- [AVCapView addSubview:cancelBtn];
- [self.view addSubview:AVCapView];
- //画上边框
- UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH- 22 * SCANVIEW_EdgeLeft, 1)];
- topView.backgroundColor = [UIColor whiteColor];
- [AVCapView addSubview:topView];
- //画左边框
- UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop , 1,VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft )];
- leftView.backgroundColor = [UIColor whiteColor];
- [AVCapView addSubview:leftView];
- //画右边框
- UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft + VIEW_WIDTH- 22 * SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop , 1,VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft + 1)];
- rightView.backgroundColor = [UIColor whiteColor];
- [AVCapView addSubview:rightView];
- //画下边框
- UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop + VIEW_WIDTH- 22 * SCANVIEW_EdgeLeft,VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft ,1 )];
- downView.backgroundColor = [UIColor whiteColor];
- [AVCapView addSubview:downView];
- //闪光灯
- UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
- btn.frame = CGRectMake(150, [UIScreen mainScreen].bounds.size.height - 100, 80, 35);
- [btn setTintColor:[UIColor grayColor]];
- [btn setTitle:@"闪光灯" forState:UIControlStateNormal];
- [btn addTarget:self action: @selector(OPEN:) forControlEvents:UIControlEventTouchUpInside];
- [AVCapView addSubview:btn];
- //画中间的基准线
- _QrCodeline = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft + 1, SCANVIEW_EdgeTop, VIEW_WIDTH- 22 * SCANVIEW_EdgeLeft - 1, 2)];
- _QrCodeline.backgroundColor = [UIColor greenColor];
- [AVCapView addSubview:_QrCodeline];
- // 先让基准线运动一次,避免定时器的时差
- [UIView animateWithDuration:1.2 animations:^{
- _QrCodeline.frame = CGRectMake(SCANVIEW_EdgeLeft + 1, VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop , VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft - 1, 2);
- }];
- [self performSelector:@selector(createTimer) withObject:nil afterDelay:0.4];
- AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
- //创建输入流
- AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
- //创建输出流
- AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
- //设置代理 在主线程里刷新
- [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
- //初始化链接对象
- session = [[AVCaptureSession alloc]init];
- //高质量采集率
- [session setSessionPreset:AVCaptureSessionPresetHigh];
- [session addInput:input];
- [session addOutput:output];
- //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
- output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
- AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
- layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
- layer.frame = CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH- 22 * SCANVIEW_EdgeLeft, 220);
- [AVCapView.layer insertSublayer:layer atIndex:0];
- //开始捕获
- [session startRunning];
- }
- #pragma mark 调用闪光灯
- - (void)OPEN:(UIButton *)btn{
- btn.selected = !btn.isSelected;
- AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
- if ([device hasTorch]) {
- [device lockForConfiguration:nil];
- if (btn.selected) {
- [device setTorchMode:AVCaptureTorchModeOn];
- }else{
- [device setTorchMode:AVCaptureTorchModeOff];
- }
- [device unlockForConfiguration];
- }
- }
- - (void)touchAVCancelBtn{
- //取消按钮的响应时间
- }
- #pragma mark 5.实现定时器、还有基准线的滚动方法
- - (void)createTimer
- {
- _timer=[NSTimer scheduledTimerWithTimeInterval:1.1 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats:YES];
- }
- - (void)stopTimer
- {
- if ([_timer isValid] == YES) {
- [_timer invalidate];
- _timer = nil;
- }
- }
- // 滚来滚去 :D :D :D
- - (void)moveUpAndDownLine
- {
- CGFloat YY = _QrCodeline.frame.origin.y;
- if (YY != VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop ) {
- [UIView animateWithDuration:1.2 animations:^{
- _QrCodeline.frame = CGRectMake(SCANVIEW_EdgeLeft + 1, VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop , VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft - 1,2);
- }];
- }else {
- [UIView animateWithDuration:1.2 animations:^{
- _QrCodeline.frame = CGRectMake(SCANVIEW_EdgeLeft + 1, SCANVIEW_EdgeTop, VIEW_WIDTH - 22 * SCANVIEW_EdgeLeft - 1,2);
- }];
- }
- }
- #pragma mark 6.扫描成功后,想干嘛干嘛,就在这个代理方法里面实现就行了
- -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
- if (metadataObjects.count>0) {
- //[session stopRunning];
- AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
- //输出扫描字符串
- NSLog(@"%@",metadataObject.stringValue);
- AudioServicesPlaySystemSound(1307);
- [session stopRunning];
- [self stopTimer];
- //[AVCapView removeFromSuperview];
- }
- }
13.webView计算高度
- //第一种:
- - (void)webViewDidFinishLoad:(UIWebView *)webView{
- float height = [[webView stringByEvaluatingJavaScriptFromString:@document.body.offsetHeight;] floatValue];
- //document.body.scrollHeight
- }
- //第二种:
- - (void) webViewDidFinishLoad:(UIWebView *)webView
- {
- CGRect frame = webView.frame;
- CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
- frame.size = fittingSize;
- webView.frame = frame;
- }
- //另外一种
- - (void)viewDidLoad {
- [super viewDidLoad];
- webview.delegate = self;
- [webview loadHTMLString:@
- fdasfda
- baseURL:nil];
- }
- - (void)webViewDidFinishLoad:(UIWebView *)webView
- {
- NSString *output = [webview stringByEvaluatingJavaScriptFromString:@document.getElementByIdx_x_x_x(foo).offsetHeight;];
- NSLog(@height: %@, output);
- }