1.//获取字符串(或汉字)首字母+ (NSString *)firstCharacterWithString:(NSString *)string{ NSMutableString *str = [NSMutableString stringWithString:string]; CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); NSString *pingyin = [str capitalizedString]; return [pingyin substringToIndex:1];}
2.//将字符串数组按照元素首字母顺序进行排序分组
+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
if (array.count == 0) {
return nil;
}
for (id obj in array) {
if (![obj isKindOfClass:[NSString class]]) {
return nil;
}
}
UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation 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;
}
//获取字符串(或汉字)首字母
+ (NSString *)firstCharacterWithString:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringToIndex:1];
}
3.//获取当前时间
//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"
+ (NSString *)currentDateWithFormat:(NSString *)format{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
return [dateFormatter stringFromDate:[NSDate date]];
}
4.//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile{
mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
if (mobile.length != 11)
{
return NO;
}else{
/**
* 移动号段正则表达式
*/
NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
/**
* 联通号段正则表达式
*/
NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
/**
* 电信号段正则表达式
*/
NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
if (isMatch1 || isMatch2 || isMatch3) {
return YES;
}else{
return NO;
}
}
}
5.//利用正则表达式验证
+ (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];
}
6.//截取view中某个区域生成一张图片
+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
UIGraphicsBeginImageContext(scope.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
CGContextTranslateCTM(context, 0, rect.size.height);//下移
CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
CGContextDrawImage(context, rect, imageRef);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(imageRef);
CGContextRelease(context);
return image;
}
7.//判断字符串中是否含有某个字符串
+ (BOOL)isHaveSpaceInString:(NSString *)string{ NSRange _range = [string rangeOfString:@" "]; if (_range.location != NSNotFound) { return YES; }else { return NO; }}
8.//判断字符串中是否含有中文
+ (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;}
9.//判断字符串是否全部为数字
+ (BOOL)isAllNum:(NSString *)string{
unichar c; for (int i=0; i
10.//绘制虚线
/* ** lineFrame: 虚线的 frame ** length: 虚线中短线的宽度 ** spacing: 虚线中短线之间的间距 ** color: 虚线中短线的颜色*/+ (UIView *)createDashedLineWithFrame:(CGRect)lineFrame lineLength:(int)length lineSpacing:(int)spacing lineColor:(UIColor *)color{ UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame]; dashedLine.backgroundColor = [UIColor clearColor]; CAShapeLayer *shapeLayer = [CAShapeLayer layer]; [shapeLayer setBounds:dashedLine.bounds]; [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))]; [shapeLayer setFillColor:[UIColor clearColor].CGColor]; [shapeLayer setStrokeColor:color.CGColor]; [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)]; [shapeLayer setLineJoin:kCALineJoinRound]; [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]]; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 0, 0); CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0); [shapeLayer setPath:path]; CGPathRelease(path); [dashedLine.layer addSublayer:shapeLayer]; return dashedLine;}
11.//压缩图片到指定文件大小
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
NSData *data = UIImageJPEGRepresentation(image, 1.0);
CGFloat dataKBytes = data.length/1000.0;
CGFloat maxQuality = 0.9f;
CGFloat lastData = dataKBytes;
while (dataKBytes > size && maxQuality > 0.01f) {
maxQuality = maxQuality - 0.01f;
data = UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length/1000.0;
if (lastData == dataKBytes) {
break;
}else{
lastData = dataKBytes;
}
}
return data;
}
1.压缩图片
[objc]view plaincopy
#pragma mark 处理图片
- (void)useImage:(UIImage*)image
{
NSLog(@"with-----%f heught-----%f",image.size.width,image.size.height);
floatscales = image.size.height/ image.size.width;//图片比例
NSLog(@"图片比例:%f",scales);
UIImage* normalImg;
if(image.size.width>300|| image.size.height>300) {
if(scales >1) {
normalImg = [selfimageWithImageSimple:imagescaledToSize:CGSizeMake(300/ scales,300)];
}else{
normalImg = [selfimageWithImageSimple:imagescaledToSize: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);
floatkk =1.0f;//图片压缩系数
intmm;//压缩后的大小
floataa =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) {
[APPRequestshowAlert:@"提示"message:@"图片过大"];
}else{
// 上传图片网络请求
}
}];
}
}
2.发布时间
[objc]view plaincopy
NSDate* timeDate = [NSDatedate];
NSTimeInterval nowInt = [timeDatetimeIntervalSince1970]*1;
NSDateFormatter *dateformatter=[[NSDateFormatteralloc]init];
[dateformattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* publishDate = [dateformatterdateFromString:[demandlist.publish_timesubstringToIndex:19]];
NSTimeInterval publishInt = [publishDatetimeIntervalSince1970]*1;
NSTimeInterval cha = nowInt - publishInt;
NSString*timeString=@"";
if(cha/3600<1) {
timeString = [NSStringstringWithFormat:@"%f", cha/60];
timeString = [timeStringsubstringToIndex:timeString.length-7];
timeString = [NSStringstringWithFormat:@"%@分钟前发布",timeString];
}
if(cha/3600>1&&cha/86400<1) {
timeString = [NSStringstringWithFormat:@"%f", cha/3600];
timeString = [timeStringsubstringToIndex:timeString.length-7];
timeString = [NSStringstringWithFormat:@"%@小时前发布",timeString];
}
if(cha/86400>1)
{
timeString = [NSStringstringWithFormat:@"%f", cha/86400];
timeString = [timeStringsubstringToIndex:timeString.length-7];
timeString = [NSStringstringWithFormat:@"%@天前发布",timeString];
}
3.返回字符串所占的尺寸
[objc]view plaincopy
//返回字符串所占用的尺寸.
-(CGSize)sizeWithFont:(UIFont*)fontmaxSize:(CGSize)maxSize
{NSDictionary*attrs = @{NSFontAttributeName : font};
return[selfboundingRectWithSize:maxSizeoptions:NSStringDrawingUsesLineFragmentOriginattributes:attrscontext:nil].size;
}
4.tableView自动滑倒某一行
[objc]view plaincopy
NSIndexPath*scrollIndexPath = [NSIndexPathindexPathForRow:10inSection:0];
[[selftableView]scrollToRowAtIndexPath:scrollIndexPath
atScrollPosition:UITableViewScrollPositionTopanimated:YES];
5.tableView刷新某个分区或某行
[objc]view plaincopy
NSIndexSet*indexSet=[[NSIndexSetalloc]initWithIndex:2];
[tableviewreloadSections:indexSetwithRowAnimation:UITableViewRowAnimationAutomatic];
//一个cell刷新
NSIndexPath*indexPath=[NSIndexPathindexPathForRow:3inSection:0];
[tableViewreloadRowsAtIndexPaths:[NSArrayarrayWithObjects:indexPath,nil]withRowAnimation:UITableViewRowAnimationNone];
6.读取plist文件
[objc]view plaincopy
NSString*plistPath = [[NSBundlemainBundle]pathForResource:@"plistdemo"ofType:@"plist"];
NSMutableDictionary*data = [[NSMutableDictionaryalloc]initWithContentsOfFile:plistPath];
7.关键字高亮
[objc]view plaincopy
label.text= [NSStringstringWithFormat:@" 视野头条:%@",home.title];
NSString*str = [NSStringstringWithFormat:@" 视野头条:%@",home.title];
NSMutableAttributedString*titleStr = [[NSMutableAttributedStringalloc]initWithString:str];
NSRange range = [strrangeOfString:@"视野头条:"];
[titleStraddAttribute:NSForegroundColorAttributeNamevalue:[UIColororangeColor]range:range];
[labelsetAttributedText:titleStr];
8.去掉字符串中的空格
[objc]view plaincopy
NSString*str =@"dhak d sh akdl ";
NSString*strUrl = [strstringByReplacingOccurrencesOfString:@" "withString:@""];
9.UIImage添加生成圆角图片的扩展API
[objc]view plaincopy
给UIImage添加生成圆角图片的扩展API:
- (UIImage*)imageWithCornerRadius:(CGFloat)radius {
CGRect rect = (CGRect){0.f,0.f,self.size};
UIGraphicsBeginImageContextWithOptions(self.size,NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPathbezierPathWithRoundedRect:rectcornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[selfdrawInRect:rect];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnimage;
}
//然后调用时就直接传一个圆角来处理:
imgView.image= [[UIImageimageNamed:@"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.正则法则
[html]view plaincopy
//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.清除缓存
[objc]view plaincopy
// 删除缓存
- (void)removeCache
{
NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES)lastObject];
NSLog(@"%@",cachePath);
NSArray*files = [[NSFileManagerdefaultManager]subpathsAtPath:cachePath];
for(NSString*p in files) {
NSString*path = [NSStringstringWithFormat:@"%@/%@", cachePath,p];
if([[NSFileManagerdefaultManager]fileExistsAtPath:path]) {
[[NSFileManagerdefaultManager]removeItemAtPath:patherror:nil];
}
}
}
// 计算清除的缓存大小
- (CGFloat)floatWithPath:(NSString*)path
{
CGFloat num =0;
NSFileManager*man = [NSFileManagerdefaultManager];
if([manfileExistsAtPath:path]) {
NSEnumerator*childFile = [[mansubpathsAtPath:path]objectEnumerator];
NSString*fileName;
while((fileName = [childFilenextObject]) !=nil) {
NSString*fileSub = [pathstringByAppendingPathComponent:fileName];
num += [selffileSizeAtPath:fileSub];
}
}
returnnum / (1024.0*1024.0);
}
//计算单个文件大小
- (longlong)fileSizeAtPath:(NSString*)file
{
NSFileManager*man = [NSFileManagerdefaultManager];
if([manfileExistsAtPath:file]) {
return[[manattributesOfItemAtPath:fileerror:nil]fileSize];
}
return0;
}
12 系统原生态二维码扫描(包括闪光灯,系统提示音)
[objc]view plaincopy
#import
#import // 系统提示音
#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 几个东东用来画框、画线:
*/
@interfaceViewController ()
{
AVCaptureSession* session;//输入输出的中间桥梁
UIView*AVCapView;//此 view 用来放置扫描框、取消按钮、说明 label
UIView*_QrCodeline;//上下移动绿色的线条
NSTimer*_timer;
}
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
[selfcreateUI];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark 4.在某个方法中(我是点击扫描按钮)创建扫描界面,开始扫描
- (void)createUI{
//创建一个 view 来放置扫描区域、说明 label、取消按钮
UIView*tempView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,320, [UIScreenmainScreen].bounds.size.height)];
AVCapView = tempView;
AVCapView.backgroundColor= [UIColorcolorWithRed:54.f/255green:53.f/255blue:58.f/255alpha:1];
UIButton*cancelBtn = [[UIButtonalloc]initWithFrame:CGRectMake(15, [UIScreenmainScreen].bounds.size.height-100,50,25)];
UILabel*label = [[UILabelalloc]initWithFrame:CGRectMake(15,268,290,60)];
label.numberOfLines=0;
label.text=@"小提示:将条形码或二维码对准上方区域中心即可";
label.textColor= [UIColorgrayColor];
[cancelBtnsetTitle:@"取消"forState:UIControlStateNormal];
[cancelBtnsetTitleColor:[UIColorgrayColor]forState:UIControlStateNormal];
[cancelBtnaddTarget:selfaction:@selector(touchAVCancelBtn)forControlEvents:UIControlEventTouchUpInside];
[AVCapViewaddSubview:label];
[AVCapViewaddSubview:cancelBtn];
[self.viewaddSubview:AVCapView];
//画上边框
UIView*topView = [[UIViewalloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH-22* SCANVIEW_EdgeLeft,1)];
topView.backgroundColor= [UIColorwhiteColor];
[AVCapViewaddSubview:topView];
//画左边框
UIView*leftView = [[UIViewalloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop ,1,VIEW_WIDTH -22* SCANVIEW_EdgeLeft )];
leftView.backgroundColor= [UIColorwhiteColor];
[AVCapViewaddSubview:leftView];
//画右边框
UIView*rightView = [[UIViewalloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft + VIEW_WIDTH-22* SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop ,1,VIEW_WIDTH -22* SCANVIEW_EdgeLeft +1)];
rightView.backgroundColor= [UIColorwhiteColor];
[AVCapViewaddSubview:rightView];
//画下边框
UIView*downView = [[UIViewalloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop + VIEW_WIDTH-22* SCANVIEW_EdgeLeft,VIEW_WIDTH -22* SCANVIEW_EdgeLeft ,1)];
downView.backgroundColor= [UIColorwhiteColor];
[AVCapViewaddSubview:downView];
//闪光灯
UIButton*btn = [UIButtonbuttonWithType:UIButtonTypeCustom];
btn.frame= CGRectMake(150, [UIScreenmainScreen].bounds.size.height-100,80,35);
[btnsetTintColor:[UIColorgrayColor]];
[btnsetTitle:@"闪光灯"forState:UIControlStateNormal];
[btnaddTarget:selfaction:@selector(OPEN:)forControlEvents:UIControlEventTouchUpInside];
[AVCapViewaddSubview:btn];
//画中间的基准线
_QrCodeline = [[UIViewalloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft +1, SCANVIEW_EdgeTop, VIEW_WIDTH-22* SCANVIEW_EdgeLeft -1,2)];
_QrCodeline.backgroundColor= [UIColorgreenColor];
[AVCapViewaddSubview:_QrCodeline];
// 先让基准线运动一次,避免定时器的时差
[UIViewanimateWithDuration:1.2animations:^{
_QrCodeline.frame= CGRectMake(SCANVIEW_EdgeLeft +1, VIEW_WIDTH -22* SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop , VIEW_WIDTH -22* SCANVIEW_EdgeLeft -1,2);
}];
[selfperformSelector:@selector(createTimer)withObject:nilafterDelay:0.4];
AVCaptureDevice* device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput* input = [AVCaptureDeviceInputdeviceInputWithDevice:deviceerror:nil];
//创建输出流
AVCaptureMetadataOutput* output = [[AVCaptureMetadataOutputalloc]init];
//设置代理 在主线程里刷新
[outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
//初始化链接对象
session = [[AVCaptureSessionalloc]init];
//高质量采集率
[sessionsetSessionPreset:AVCaptureSessionPresetHigh];
[sessionaddInput:input];
[sessionaddOutput:output];
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer* layer = [AVCaptureVideoPreviewLayerlayerWithSession:session];
layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
layer.frame= CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH-22* SCANVIEW_EdgeLeft,220);
[AVCapView.layerinsertSublayer:layeratIndex:0];
//开始捕获
[sessionstartRunning];
}
#pragma mark 调用闪光灯
- (void)OPEN:(UIButton*)btn{
btn.selected= !btn.isSelected;
AVCaptureDevice*device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
if([devicehasTorch]) {
[devicelockForConfiguration:nil];
if(btn.selected) {
[devicesetTorchMode:AVCaptureTorchModeOn];
}else{
[devicesetTorchMode:AVCaptureTorchModeOff];
}
[deviceunlockForConfiguration];
}
}
- (void)touchAVCancelBtn{
//取消按钮的响应时间
}
#pragma mark 5.实现定时器、还有基准线的滚动方法
- (void)createTimer
{
_timer=[NSTimerscheduledTimerWithTimeInterval:1.1target:selfselector:@selector(moveUpAndDownLine)userInfo:nilrepeats:YES];
}
- (void)stopTimer
{
if([_timerisValid] ==YES) {
[_timerinvalidate];
_timer =nil;
}
}
// 滚来滚去 :D :D :D
- (void)moveUpAndDownLine
{
CGFloat YY = _QrCodeline.frame.origin.y;
if(YY != VIEW_WIDTH -22* SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop ) {
[UIViewanimateWithDuration:1.2animations:^{
_QrCodeline.frame= CGRectMake(SCANVIEW_EdgeLeft +1, VIEW_WIDTH -22* SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop , VIEW_WIDTH -22* SCANVIEW_EdgeLeft -1,2);
}];
}else{
[UIViewanimateWithDuration:1.2animations:^{
_QrCodeline.frame= CGRectMake(SCANVIEW_EdgeLeft +1, SCANVIEW_EdgeTop, VIEW_WIDTH -22* SCANVIEW_EdgeLeft -1,2);
}];
}
}
#pragma mark 6.扫描成功后,想干嘛干嘛,就在这个代理方法里面实现就行了
-(void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputMetadataObjects:(NSArray*)metadataObjectsfromConnection:(AVCaptureConnection*)connection{
if(metadataObjects.count>0) {
//[session stopRunning];
AVMetadataMachineReadableCodeObject* metadataObject = [metadataObjects objectAtIndex :0];
//输出扫描字符串
NSLog(@"%@",metadataObject.stringValue);
AudioServicesPlaySystemSound(1307);
[sessionstopRunning];
[selfstopTimer];
//[AVCapView removeFromSuperview];
}
}
13.webView计算高度
[objc]view plaincopy
//第一种:
- (void)webViewDidFinishLoad:(UIWebView*)webView{
floatheight = [[webViewstringByEvaluatingJavaScriptFromString:@document.body.offsetHeight;]floatValue];
//document.body.scrollHeight
}
//第二种:
- (void)webViewDidFinishLoad:(UIWebView*)webView
{
CGRect frame = webView.frame;
CGSize fittingSize = [webViewsizeThatFits:CGSizeZero];
frame.size= fittingSize;
webView.frame= frame;
}
//另外一种
- (void)viewDidLoad {
[superviewDidLoad];
webview.delegate=self;
[webviewloadHTMLString:@
fdasfda
baseURL:nil];
}
- (void)webViewDidFinishLoad:(UIWebView*)webView
{
NSString*output = [webviewstringByEvaluatingJavaScriptFromString:@document.getElementByIdx_x_x_x(foo).offsetHeight;];
NSLog(@height: %@, output);
}
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;
}
returnsize;
}
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;
}
returnsize;
}
3.将字符串数组按照元素首字母顺序进行排序分组
+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array
{
if(array.count == 0) {
returnnil;
}
for(id obj in array) {
if(![obj isKindOfClass:[NSStringclass]]) {
returnnil;
}
}
UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
//创建27个分组数组
for(inti = 0; i < indexedCollation.sectionTitles.count; i++) {
NSMutableArray *obj = [NSMutableArray array];
[objects addObject:obj];
}
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
//按字母顺序进行分组
NSInteger lastIndex = -1;
for(inti = 0; i < array.count; i++) {
NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
[[objects objectAtIndex:index] addObject:array[i]];
lastIndex = index;
}
//去掉空数组
for(inti = 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];
returndic;
}
4.将字符串数组按照元素首字母顺序进行排序分组
+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array
{
if(array.count == 0) {
returnnil;
}
for(id obj in array) {
if(![obj isKindOfClass:[NSStringclass]]) {
returnnil;
}
}
UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
//创建27个分组数组
for(inti = 0; i < indexedCollation.sectionTitles.count; i++) {
NSMutableArray *obj = [NSMutableArray array];
[objects addObject:obj];
}
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
//按字母顺序进行分组
NSInteger lastIndex = -1;
for(inti = 0; i < array.count; i++) {
NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
[[objects objectAtIndex:index] addObject:array[i]];
lastIndex = index;
}
//去掉空数组
for(inti = 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];
returndic;
}
5.对图片进行滤镜处理
// 怀旧 --> 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);
returnresultImage;
}
6.对图片进行模糊处理
// 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);
returnresultImage;
}else{
returnnil;
}
}
7.跳转到系统的相关界面:
/*
* 需要添加一个字段
* 蓝色的项目工程文件 -> Info -> URL Types -> 添加一个 -> 设置URL Sch**** 为 prefs的url
NSURL *url = [NSURL URLWithString:@"prefs:root=WIFI"];
[[UIApplication sharedApplication] openURL:url];
跳转到其他的界面的字段(不全,详细看链接)
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
AirplaneModeOn— prefs:root=AIRPLANE_MODE
Auto-Lock — prefs:root=General&path=AUTOLOCK
Brightness — prefs:root=Brightness
Bluetooth — prefs:root=General&path=Bluetooth
Date& Time — prefs:root=General&path=DATE_AND_TIME
FaceTime — prefs:root=FACETIME
General— prefs:root=General
原文链接:http://www.jianshu.com/p/19602f48309b
*/
8.创建一张实时模糊效果 View (毛玻璃效果)
//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;
returneffectView;
}
9.设置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;
}
10.让Plain风格的TableView的区头可以”不悬停”(可以直接百度搜到):
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if(scrollView == self.myTab) {
CGFloat sectionHeaderHeight = 40;
if(scrollView.contentOffset.y=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
}elseif(scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}