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.//將字符串?dāng)?shù)組按照元素首字母順序進(jìn)行排序分組
+ (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];
//創(chuàng)建27個(gè)分組數(shù)組
for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
NSMutableArray *obj = [NSMutableArray array];
[objects addObject:obj];
}
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
//按字母順序進(jìn)行分組
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;
}
//去掉空數(shù)組
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.//獲取當(dāng)前時(shí)間
//format: @"yyyy-MM-dd HH:mm:ss"袍啡、@"yyyy年MM月dd日 HH時(shí)mm分ss秒"
+ (NSString *)currentDateWithFormat:(NSString *)format{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
return [dateFormatter stringFromDate:[NSDate date]];
}
4.//判斷手機(jī)號碼格式是否正確
+ (BOOL)valiMobile:(NSString *)mobile{
mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
if (mobile.length != 11)
{
return NO;
}else{
/**
* 移動號段正則表達(dá)式
*/
NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
/**
* 聯(lián)通號段正則表達(dá)式
*/
NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
/**
* 電信號段正則表達(dá)式
*/
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.//利用正則表達(dá)式驗(yàn)證
+ (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中某個(gè)區(qū)域生成一張圖片
+ (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.//判斷字符串中是否含有某個(gè)字符串
+ (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.//判斷字符串是否全部為數(shù)字
+ (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;//圖片壓縮系數(shù)
intmm;//壓縮后的大小
floataa?=1.0f;//圖片壓縮系數(shù)變化步長(可變)
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);//最后壓縮結(jié)果
if(newData.length/1024>300)?{
[APPRequestshowAlert:@"提示"message:@"圖片過大"];
}else{
//?上傳圖片網(wǎng)絡(luò)請求
}
}];
}
}
2.發(fā)布時(shí)間
[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:@"%@分鐘前發(fā)布",timeString];
}
if(cha/3600>1&&cha/86400<1)?{
timeString?=?[NSStringstringWithFormat:@"%f",?cha/3600];
timeString?=?[timeStringsubstringToIndex:timeString.length-7];
timeString?=?[NSStringstringWithFormat:@"%@小時(shí)前發(fā)布",timeString];
}
if(cha/86400>1)
{
timeString?=?[NSStringstringWithFormat:@"%f",?cha/86400];
timeString?=?[timeStringsubstringToIndex:timeString.length-7];
timeString?=?[NSStringstringWithFormat:@"%@天前發(fā)布",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刷新某個(gè)分區(qū)或某行
[objc]view plaincopy
NSIndexSet*indexSet=[[NSIndexSetalloc]initWithIndex:2];
[tableviewreloadSections:indexSetwithRowAnimation:UITableViewRowAnimationAutomatic];
//一個(gè)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.關(guān)鍵字高亮
[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添加生成圓角圖片的擴(kuò)展API
[objc]view plaincopy
給UIImage添加生成圓角圖片的擴(kuò)展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;
}
//然后調(diào)用時(shí)就直接傳一個(gè)圓角來處理:
imgView.image=?[[UIImageimageNamed:@"test"]hyb_imageWithCornerRadius:4];
//最直接的方法就是使用如下屬性設(shè)置:
imgView.layer.cornerRadius=10;
//?這一行代碼是很消耗性能的
imgView.clipsToBounds=YES;
//好處是使用簡單,操作方便范咨。壞處是離屏渲染(off-screen-rendering)需要消耗性能笋籽。對于圖片比較多的視圖上季二,不建議使用這種方法來設(shè)置圓角。通常來說译暂,計(jì)算機(jī)系統(tǒng)中CPU第煮、GPU、顯示器是協(xié)同工作的放仗。CPU計(jì)算好顯示內(nèi)容提交到GPU润绎,GPU渲染完成后將渲染結(jié)果放入幀緩沖區(qū)。
//簡單來說匙监,離屏渲染,導(dǎo)致本該GPU干的活小作,結(jié)果交給了CPU來干亭姥,而CPU又不擅長GPU干的活,于是拖慢了UI層的FPS(數(shù)據(jù)幀率)顾稀,并且離屏需要?jiǎng)?chuàng)建新的緩沖區(qū)和上下文切換达罗,因此消耗較大的性能。
10.正則法則
[html]view plaincopy
//1.驗(yàn)證郵箱
+?(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.驗(yàn)證手機(jī)(簡單的)
+?(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];
}
//驗(yàn)證手機(jī)(復(fù)雜的)
+?(BOOL)validatePhone:(NSString?*)phone
{
/**
*?手機(jī)號碼
*?移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
*?聯(lián)通: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?????????*?中國聯(lián)通: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?????????*?大陸地區(qū)固話及小靈通
26?????????*?區(qū)號: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];
}
}
}
//?計(jì)算清除的緩存大小
-?(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);
}
//計(jì)算單個(gè)文件大小
-?(longlong)fileSizeAtPath:(NSString*)file
{
NSFileManager*man?=?[NSFileManagerdefaultManager];
if([manfileExistsAtPath:file])?{
return[[manattributesOfItemAtPath:fileerror:nil]fileSize];
}
return0;
}
12 系統(tǒng)原生態(tài)二維碼掃描(包括閃光燈静秆,系統(tǒng)提示音)
[objc]view plaincopy
#import?
#import??//?系統(tǒng)提示音
#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
/*
*********注意?:系統(tǒng)原生態(tài)二維碼掃描?蘋果官方目前不支持掃掃描圖冊圖片?************
1.第一步?引入框架?AVFoundation.framework
2.第二步?聲明代理:AVCaptureMetadataOutputObjectsDelegate?粮揉。?define?幾個(gè)東東用來畫框、畫線:
*/
@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.在某個(gè)方法中(我是點(diǎn)擊掃描按鈕)創(chuàng)建掃描界面,開始掃描
-?(void)createUI{
//創(chuàng)建一個(gè)?view?來放置掃描區(qū)域殊橙、說明?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=@"小提示:將條形碼或二維碼對準(zhǔn)上方區(qū)域中心即可";
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];
//畫中間的基準(zhǔn)線
_QrCodeline?=?[[UIViewalloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft?+1,?SCANVIEW_EdgeTop,?VIEW_WIDTH-22*?SCANVIEW_EdgeLeft?-1,2)];
_QrCodeline.backgroundColor=?[UIColorgreenColor];
[AVCapViewaddSubview:_QrCodeline];
//?先讓基準(zhǔn)線運(yùn)動一次,避免定時(shí)器的時(shí)差
[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];
//創(chuàng)建輸入流
AVCaptureDeviceInput*?input?=?[AVCaptureDeviceInputdeviceInputWithDevice:deviceerror:nil];
//創(chuàng)建輸出流
AVCaptureMetadataOutput*?output?=?[[AVCaptureMetadataOutputalloc]init];
//設(shè)置代理?在主線程里刷新
[outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
//初始化鏈接對象
session?=?[[AVCaptureSessionalloc]init];
//高質(zhì)量采集率
[sessionsetSessionPreset:AVCaptureSessionPresetHigh];
[sessionaddInput:input];
[sessionaddOutput:output];
//設(shè)置掃碼支持的編碼格式(如下設(shè)置條形碼和二維碼兼容)
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?調(diào)用閃光燈
-?(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{
//取消按鈕的響應(yīng)時(shí)間
}
#pragma?mark?5.實(shí)現(xiàn)定時(shí)器膨蛮、還有基準(zhǔn)線的滾動方法
-?(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.掃描成功后叠纹,想干嘛干嘛,就在這個(gè)代理方法里面實(shí)現(xiàn)就行了
-(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計(jì)算高度
[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.將字符串?dāng)?shù)組按照元素首字母順序進(jìn)行排序分組
+?(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];
//創(chuàng)建27個(gè)分組數(shù)組
for(inti?=?0;?i?<?indexedCollation.sectionTitles.count;?i++)?{
NSMutableArray?*obj?=?[NSMutableArray?array];
[objects?addObject:obj];
}
NSMutableArray?*keys?=?[NSMutableArray?arrayWithCapacity:objects.count];
//按字母順序進(jìn)行分組
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;
}
//去掉空數(shù)組
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.將字符串?dāng)?shù)組按照元素首字母順序進(jìn)行排序分組
+?(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];
//創(chuàng)建27個(gè)分組數(shù)組
for(inti?=?0;?i?<?indexedCollation.sectionTitles.count;?i++)?{
NSMutableArray?*obj?=?[NSMutableArray?array];
[objects?addObject:obj];
}
NSMutableArray?*keys?=?[NSMutableArray?arrayWithCapacity:objects.count];
//按字母順序進(jìn)行分組
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;
}
//去掉空數(shù)組
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.對圖片進(jìn)行濾鏡處理
//?懷舊?-->?CIPhotoEffectInstant?????????????????????????單色?-->?CIPhotoEffectMono
//?黑白?-->?CIPhotoEffectNoir????????????????????????????褪色?-->?CIPhotoEffectFade
//?色調(diào)?-->?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.對圖片進(jìn)行模糊處理
//?CIGaussianBlur?--->?高斯模糊
//?CIBoxBlur??????--->?均值模糊(Available?in?iOS?9.0?and?later)
//?CIDiscBlur?????--->?環(huán)形卷積模糊(Available?in?iOS?9.0?and?later)
//?CIMedianFilter?--->?中值模糊,?用于消除圖像噪點(diǎn),?無需設(shè)置radius(Available?in?iOS?9.0?and?later)
//?CIMotionBlur???--->?運(yùn)動模糊,?用于模擬相機(jī)移動拍攝時(shí)的掃尾效果(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.跳轉(zhuǎn)到系統(tǒng)的相關(guān)界面:
/*
*??需要添加一個(gè)字段
*??藍(lán)色的項(xiàng)目工程文件?->?Info?->?URL?Types?->?添加一個(gè)?->?設(shè)置URL??Sch****?為?prefs的url
NSURL?*url?=?[NSURL?URLWithString:@"prefs:root=WIFI"];
[[UIApplication?sharedApplication]?openURL:url];
跳轉(zhuǎn)到其他的界面的字段(不全,詳細(xì)看鏈接)
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.reibang.com/p/19602f48309b
*/
8.創(chuàng)建一張實(shí)時(shí)模糊效果?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.設(shè)置Label的行間距
+?(void)setLineSpaceWithString:(UILabel?*)label
{
NSMutableAttributedString?*attributedString?=
[[NSMutableAttributedString?alloc]?initWithString:label.text];
NSMutableParagraphStyle?*paragraphStyle?=??[[NSMutableParagraphStyle?alloc]?init];
[paragraphStyle?setLineSpacing:3];
//調(diào)整行間距
[attributedString?addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0,?[label.text?length])];
label.attributedText?=?attributedString;
}
10.讓Plain風(fēng)格的TableView的區(qū)頭可以”不懸统ǜ穑”(可以直接百度搜到):
-?(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);
}
}
}