感謝作者:Arackboss
原文鏈接:http://www.reibang.com/p/c07324ae44f3
判斷郵箱格式是否正確的代碼
-(BOOL)isValidateEmail:(NSString*)email{NSString*emailRegex =@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";NSPredicate*emailTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES%@",emailRegex];return[emailTest evaluateWithObject:email];}
判斷是否有特殊字符
+(BOOL)isContainsSpecialCharacters:(NSString*)string{NSString*regex =@".*[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]+.*";NSPredicate*predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", regex];if([predicate evaluateWithObject:string]==YES) {returnYES;? ? ? ? ? ? }else{returnNO;? ? }? ? }
判斷是否包含漢字
+(BOOL)isChinese:(NSString*)str {for(inti=0; i< [str length];i++){inta = [str characterAtIndex:i];if( a >0x4e00&& a <0x9fff){returnYES;? ? ? ? }? ? ? ? ? ? }returnNO;}
身份證號(hào)碼驗(yàn)證
#pragma mark -身份證號(hào)全校驗(yàn)+ (BOOL)verifyIDCardNumber:(NSString*)IDCardNumber{? IDCardNumber = [IDCardNumber stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];if([IDCardNumber length] !=18)? {returnNO;? }NSString*mmdd =@"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";NSString*leapMmdd =@"0229";NSString*year =@"(19|20)[0-9]{2}";NSString*leapYear =@"(19|20)(0[48]|[2468][048]|[13579][26])";NSString*yearMmdd = [NSStringstringWithFormat:@"%@%@", year, mmdd];NSString*leapyearMmdd = [NSStringstringWithFormat:@"%@%@", leapYear, leapMmdd];NSString*yyyyMmdd = [NSStringstringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd,@"20000229"];NSString*area =@"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";NSString*regex = [NSStringstringWithFormat:@"%@%@%@", area, yyyyMmdd? ,@"[0-9]{3}[0-9Xx]"];NSPredicate*regexTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", regex];if(![regexTest evaluateWithObject:IDCardNumber])? {returnNO;? }intsummary = ([IDCardNumber substringWithRange:NSMakeRange(0,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(10,1)].intValue) *7+ ([IDCardNumber substringWithRange:NSMakeRange(1,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(11,1)].intValue) *9+ ([IDCardNumber substringWithRange:NSMakeRange(2,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(12,1)].intValue) *10+ ([IDCardNumber substringWithRange:NSMakeRange(3,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(13,1)].intValue) *5+ ([IDCardNumber substringWithRange:NSMakeRange(4,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(14,1)].intValue) *8+ ([IDCardNumber substringWithRange:NSMakeRange(5,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(15,1)].intValue) *4+ ([IDCardNumber substringWithRange:NSMakeRange(6,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(16,1)].intValue) *2+ [IDCardNumber substringWithRange:NSMakeRange(7,1)].intValue *1+ [IDCardNumber substringWithRange:NSMakeRange(8,1)].intValue *6+ [IDCardNumber substringWithRange:NSMakeRange(9,1)].intValue *3;NSIntegerremainder = summary %11;NSString*checkBit =@"";NSString*checkString =@"10X98765432";? checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判斷校驗(yàn)位return[checkBit isEqualToString:[[IDCardNumber substringWithRange:NSMakeRange(17,1)] uppercaseString]];}
判斷字符串是否為空
+(NSString *)stringIsEmpty:(NSString *)str{
NSString *string=[NSString stringWithFormat:@"%@",str];
if ([string isEqualToString:@""]||[string isEqualToString:@"(null)"]||[string isEqualToString:@""]||string==nil||[string isEqual:[NSNull class]]) {
string=@"";
}
return string;
}
壓縮圖片
/**
*? 實(shí)現(xiàn)圖片的縮小或者放大
*
*? @param size? 大小范圍
*
*? @return 新的圖片
*/-(UIImage*)scaleImageWithSize:(CGSize)size{UIGraphicsBeginImageContextWithOptions(size,NO,0);//size 為CGSize類型,即你所需要的圖片尺寸[selfdrawInRect:CGRectMake(0,0, size.width, size.height)];UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnscaledImage;//返回的就是已經(jīng)改變的圖片}
讓網(wǎng)絡(luò)加載圖片有個(gè)動(dòng)畫(huà)效果(前提是導(dǎo)入了SDWebImage)
-(void)animationWithImage:(NSString*)imageName{? ? [selfsd_setImageWithURL:[NSURLURLWithString:imageName] placeholderImage:nilcompleted:^(UIImage*image,NSError*error, SDImageCacheType cacheType,NSURL*imageURL) {if(image && cacheType == SDImageCacheTypeNone)? ? ? ? {self.alpha =0;? ? ? ? ? ? [UIViewanimateWithDuration:0.5animations:^{self.alpha =1.0f;? ? ? ? ? ? }];? ? ? ? ? ? ? ? ? ? }else{self.alpha =1.0f;? ? ? ? }? ? }];}
根據(jù)字符串的長(zhǎng)度計(jì)算高度
+ (CGSize)sizeWithString:(NSString*)string font:(CGFloat)font maxWidth:(CGFloat)maxWidth{NSDictionary*attributesDict = @{NSFontAttributeName:FONT(font)};CGSizemaxSize =CGSizeMake(maxWidth, MAXFLOAT);CGRectsubviewRect = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOriginattributes:attributesDict context:nil];returnsubviewRect.size;? ? }
拼接屬性字符串玩徊,在電商類應(yīng)用用的比較多(比如價(jià)格,市場(chǎng)價(jià)和銷售價(jià)渣蜗,此時(shí)可以用一個(gè)lable搞定,而不用兩個(gè)label)
+(NSAttributedString*)recombinePrice:(CGFloat)CNPriceorderPrice:(CGFloat)unitPrice{NSMutableAttributedString*mutableAttributeStr = [[NSMutableAttributedStringalloc] init];NSAttributedString*string1 = [[NSAttributedStringalloc] initWithString:[NSStringstringWithFormat:@"¥%.f",unitPrice] attributes:@{NSForegroundColorAttributeName: [UIColorredColor],NSFontAttributeName: [UIFontboldSystemFontOfSize:12]}];NSAttributedString*string2 = [[NSAttributedStringalloc] initWithString:[NSStringstringWithFormat:@"¥%.f",CNPrice] attributes:@{NSForegroundColorAttributeName: [UIColorlightGrayColor],NSFontAttributeName: [UIFontboldSystemFontOfSize:11],NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),NSStrikethroughColorAttributeName: [UIColorlightGrayColor]}];? ? [mutableAttributeStr appendAttributedString:string1];? ? [mutableAttributeStr appendAttributedString:string2];returnmutableAttributeStr;}
調(diào)整label行間距
NSMutableAttributedString*attributedString = [[NSMutableAttributedStringalloc] initWithString:string];NSMutableParagraphStyle*paragraphStyle = [[NSMutableParagraphStylealloc] init];? ? paragraphStyle.lineSpacing = lineSpace;// 調(diào)整行間距NSRangerange =NSMakeRange(0, [string length]);? ? [attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:range];returnattributedString;}
創(chuàng)建導(dǎo)航欄按鈕
+ (UIBarButtonItem*)itemWithImageName:(NSString*)imageName highImageName:(NSString*)highImageName target:(id)target action:(SEL)action{UIButton*button = [[UIButtonalloc] initWithFrame:CGRectMake(0,0,40,30)];? ? [button setBackgroundImage:[UIImageimageNamed:imageName] forState:UIControlStateNormal];? ? [button setBackgroundImage:[UIImageimageNamed:highImageName] forState:UIControlStateHighlighted];? ? button.size = button.currentBackgroundImage.size;//按鈕的尺寸為按鈕的背景圖片的尺寸[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];return[[UIBarButtonItemalloc] initWithCustomView:button];}
數(shù)組的安全操作
- (id)h_safeObjectAtIndex:(NSUInteger)index{if(self.count ==0) {NSLog(@"--- mutableArray have no objects ---");return(nil);? ? }if(index > MAX(self.count -1,0)) {NSLog(@"--- index:%li out of mutableArray range ---", (long)index);return(nil);? ? }return([selfobjectAtIndex:index]);}
獲取當(dāng)前時(shí)間
-(NSDate*)getCurrentDate{NSDate*senddate = [NSDatedate];NSDateFormatter*dateformatter = [[NSDateFormatteralloc] init];? ? [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];NSString*date1 = [dateformatter stringFromDate:senddate];return[selfstringToDate:date1 withDateFormat:@"YYYY-MM-dd HH:mm:ss"]; }
比較兩個(gè)時(shí)間的大小
-(int)compareDate:(NSDate*)date01 withDate:(NSDate*)date02{intci;NSDateFormatter*df = [[NSDateFormatteralloc] init];? ? [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];NSComparisonResultresult = [date01 compare:date02];switch(result)? ? {//date02比date01大caseNSOrderedAscending: ci=1;break;//date02比date01小caseNSOrderedDescending: ci=-1;break;//date02=date01caseNSOrderedSame: ci=0;break;default:NSLog(@"erorr dates %@, %@", date01, date02);break;? ? }returnci;}
日期格式轉(zhuǎn)字符串
//日期格式轉(zhuǎn)字符串- (NSString*)dateToString:(NSDate*)date withDateFormat:(NSString*)format{NSDateFormatter*dateFormatter = [[NSDateFormatteralloc] init];? [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];? [dateFormatter setTimeZone:[NSTimeZonetimeZoneForSecondsFromGMT:8*3600]];NSString*strDate = [dateFormatter stringFromDate:date];returnstrDate;}
字符串轉(zhuǎn)日期格式
- (NSDate*)stringToDate:(NSString*)dateString withDateFormat:(NSString*)format{NSDateFormatter*dateFormatter = [[NSDateFormatteralloc] init];? ? [dateFormatter setTimeZone:[NSTimeZonetimeZoneForSecondsFromGMT:8*3600]];? ? [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];NSDate*retdate = [dateFormatter dateFromString:dateString];returnretdate;}
將世界時(shí)間轉(zhuǎn)化為中國(guó)區(qū)時(shí)間
- (NSDate*)worldTimeToChinaTime:(NSDate*)date{NSTimeZone*timeZone = [NSTimeZonesystemTimeZone];NSIntegerinterval = [timeZone secondsFromGMTForDate:date];NSDate*localeDate = [date? dateByAddingTimeInterval:interval];returnlocaleDate;}
傳入今天的時(shí)間递宅,返回明天的時(shí)間
//傳入今天的時(shí)間,返回明天的時(shí)間- (NSString*)GetTomorrowDay:(NSDate*)aDate {NSCalendar*gregorian = [[NSCalendaralloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];NSDateComponents*components = [gregorian components:NSCalendarUnitWeekday|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:aDate];? ? [components setDay:([components day]+1)];NSDate*beginningOfWeek = [gregorian dateFromComponents:components];NSDateFormatter*dateday = [[NSDateFormatteralloc] init];? ? [dateday setDateFormat:@"yyyy-MM-dd"];return[dateday stringFromDate:beginningOfWeek];}
字符串MD5加密
/** MD5加密得到sign字符串*/+(NSString*) md5String:(NSString*) input {constchar*cStr = [input UTF8String];unsignedchardigest[CC_MD5_DIGEST_LENGTH];? ? CC_MD5( cStr, (CC_LONG)strlen(cStr), digest );// This is the md5 callNSMutableString*output = [NSMutableStringstringWithCapacity:CC_MD5_DIGEST_LENGTH *2];for(inti =0; i < CC_MD5_DIGEST_LENGTH; i++)? ? ? ? [output appendFormat:@"%02x", digest[i]];returnoutput;}
字符串base64加密
+ (NSString*)base64StringFromText:(NSString*)text{if(text && ![text isEqualToString:LocalStr_None]) {//取項(xiàng)目的bundleIdentifier作為KEY? 改動(dòng)了此處//NSString *key = [[NSBundle mainBundle] bundleIdentifier];NSData*data = [text dataUsingEncoding:NSUTF8StringEncoding];//IOS 自帶DES加密 Begin? 改動(dòng)了此處//data = [self DESEncrypt:data WithKey:key];//IOS 自帶DES加密 Endreturn[selfbase64EncodedStringFrom:data];? ? }else{returnLocalStr_None;? ? }}
base64解密字符串
/** 解密 */+ (NSString*)textFromBase64String:(NSString*)base64{if(base64 && ![base64 isEqualToString:LocalStr_None]) {//取項(xiàng)目的bundleIdentifier作為KEY? 改動(dòng)了此處//NSString *key = [[NSBundle mainBundle] bundleIdentifier];NSData*data = [selfdataWithBase64EncodedString:base64];//IOS 自帶DES解密 Begin? ? 改動(dòng)了此處//data = [self DESDecrypt:data WithKey:key];//IOS 自帶DES加密 Endreturn[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];? ? }else{returnLocalStr_None;? ? }}
字符串反轉(zhuǎn)
**字符串反轉(zhuǎn)**//第一種:- (NSString*)reverseWordsInString:(NSString*)str{NSMutableString*newString = [[NSMutableStringalloc] initWithCapacity:str.length];for(NSIntegeri = str.length -1; i >=0; i --)? ? ? {unicharch = [str characterAtIndex:i];? ? ? ? ? ? [newString appendFormat:@"%c", ch];? ? ? }returnnewString;}
tableView刷新指定行
[tabelView reloadRowsAtIndexPaths:[NSArrayarrayWithObjects:[NSIndexPathindexPathForRow:IndexPath.row inSection:IndexPath.section],nil] withRowAnimation:UITableViewRowAnimationNone];
tableView刷新指定組
NSIndexSet*indexSet=[[NSIndexSetalloc]initWithIndex:2];? ? [tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
將十六進(jìn)制顏色轉(zhuǎn)換為 UIColor 對(duì)象
+ (UIColor*)colorWithHexString:(NSString*)color{NSString*cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]] uppercaseString];// String should be 6 or 8 charactersif([cString length] <6) {return[UIColorclearColor];? ? }// strip "0X" or "#" if it appearsif([cString hasPrefix:@"0X"])? ? ? ? cString = [cString substringFromIndex:2];if([cString hasPrefix:@"#"])? ? ? ? cString = [cString substringFromIndex:1];if([cString length] !=6)return[UIColorclearColor];// Separate into r, g, b substringsNSRangerange;? ? range.location =0;? ? range.length =2;//rNSString*rString = [cString substringWithRange:range];//grange.location =2;NSString*gString = [cString substringWithRange:range];//brange.location =4;NSString*bString = [cString substringWithRange:range];// Scan valuesunsignedintr, g, b;? ? [[NSScannerscannerWithString:rString] scanHexInt:&r];? ? [[NSScannerscannerWithString:gString] scanHexInt:&g];? ? [[NSScannerscannerWithString:bString] scanHexInt:&b];return[UIColorcolorWithRed:((float) r /255.0f) green:((float) g /255.0f) blue:((float) b /255.0f) alpha:1.0f];}
全屏截圖
+ (UIImage*)shotScreen{UIWindow*window = [UIApplicationsharedApplication].keyWindow;UIGraphicsBeginImageContext(window.bounds.size);? ? [window.layer renderInContext:UIGraphicsGetCurrentContext()];UIImage*image =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnimage;}
截取view中某個(gè)區(qū)域生成一張圖片
+ (UIImage*)shotWithView:(UIView*)view scope:(CGRect)scope{CGImageRefimageRef =CGImageCreateWithImageInRect([selfshotWithView:view].CGImage, scope);UIGraphicsBeginImageContext(scope.size);CGContextRefcontext =UIGraphicsGetCurrentContext();CGRectrect =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);returnimage;}
給Image加圓角
給UIImage添加生成圓角圖片的擴(kuò)展API:? - (UIImage*)imageWithCornerRadius:(CGFloat)radius {CGRectrect = (CGRect){0.f,0.f,self.size};UIGraphicsBeginImageContextWithOptions(self.size,NO,UIScreen.mainScreen.scale);CGContextAddPath(UIGraphicsGetCurrentContext(),? ? ? ? ? ? ? ? ? ? [UIBezierPathbezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);CGContextClip(UIGraphicsGetCurrentContext());? ? [selfdrawInRect:rect];UIImage*image =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnimage;? }//然后調(diào)用時(shí)就直接傳一個(gè)圓角來(lái)處理:? imgView.image = [[UIImageimageNamed:@"test"] hyb_imageWithCornerRadius:4];//最直接的方法就是使用如下屬性設(shè)置:? imgView.layer.cornerRadius =10;// 這一行代碼是很消耗性能的? imgView.clipsToBounds =YES;//好處是使用簡(jiǎn)單,操作方便。壞處是離屏渲染(off-screen-rendering)需要消耗性能握童。對(duì)于圖片比較多的視圖上,不建議使用這種方法來(lái)設(shè)置圓角叛赚。通常來(lái)說(shuō)澡绩,計(jì)算機(jī)系統(tǒng)中CPU、GPU俺附、顯示器是協(xié)同工作的肥卡。CPU計(jì)算好顯示內(nèi)容提交到GPU,GPU渲染完成后將渲染結(jié)果放入幀緩沖區(qū)昙读。? //簡(jiǎn)單來(lái)說(shuō)召调,離屏渲染膨桥,導(dǎo)致本該GPU干的活蛮浑,結(jié)果交給了CPU來(lái)干唠叛,而CPU又不擅長(zhǎng)GPU干的活,于是拖慢了UI層的FPS(數(shù)據(jù)幀率)沮稚,并且離屏需要?jiǎng)?chuàng)建新的緩沖區(qū)和上下文切換艺沼,因此消耗較大的性能。
刪除緩存
- (void)removeCache? {NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) lastObject];NSLog(@"%@",cachePath);NSArray*files = [[NSFileManagerdefaultManager] subpathsAtPath:cachePath];for(NSString*pinfiles) {NSString*path = [NSStringstringWithFormat:@"%@/%@", cachePath, p];if([[NSFileManagerdefaultManager] fileExistsAtPath:path]) {? ? ? ? ? ? ? [[NSFileManagerdefaultManager] removeItemAtPath:path error:nil];? ? ? ? ? }? ? ? }? }
計(jì)算清除的緩存大小
- (CGFloat)floatWithPath:(NSString*)path? {CGFloatnum =0;NSFileManager*man = [NSFileManagerdefaultManager];if([man fileExistsAtPath:path]) {NSEnumerator*childFile = [[man subpathsAtPath:path] objectEnumerator];NSString*fileName;while((fileName = [childFile nextObject]) !=nil) {NSString*fileSub = [path stringByAppendingPathComponent:fileName];? ? ? ? ? ? ? num += [selffileSizeAtPath:fileSub];? ? ? ? ? }? ? ? }returnnum / (1024.0*1024.0);? }
計(jì)算單個(gè)文件大小
- (longlong)fileSizeAtPath:(NSString*)file? {NSFileManager*man = [NSFileManagerdefaultManager];if([man fileExistsAtPath:file]) {return[[man attributesOfItemAtPath:file error:nil] fileSize];? ? ? }return0;? }
通過(guò)視圖蕴掏,尋找父控制器
- (UIViewController *)viewController{for(UIView*next= [selfsuperview];next;next=next.superview) {? ? ? ? UIResponder *nextResponder = [nextnextResponder];if([nextResponderisKindOfClass:[UIViewControllerclass]]) {return(UIViewController *)nextResponder;? ? ? ? }? ? }returnnil;}
給textField加上右邊的視圖
UIButton*eyeBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];? [eyeBtn setImage:[UIImageimageNamed:@"icon_close_eye"] forState:UIControlStateNormal];? [eyeBtn setImage:[UIImageimageNamed:@"icon_open_eye"] forState:UIControlStateSelected];? ? ? ? eyeBtn.width =30;? ? ? ? eyeBtn.height =30;? ? ? ? _passwordField.rightView = eyeBtn;? ? ? ? [eyeBtn addTarget:selfaction:@selector(showPwd:) forControlEvents:UIControlEventTouchUpInside];? ? ? ? _passwordField.rightViewMode =UITextFieldViewModeAlways;
UITableViewCell選中后其子視圖顏色會(huì)改變障般,重寫(xiě)下面兩個(gè)方法可以避免UI出入
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {? ? [supersetHighlighted:highlighted animated:animated];self.lineview.backgroundColor = MColor;}- (void)setSelected:(BOOL)selected animated:(BOOL)animated {? ? [supersetSelected:selected animated:animated];self.lineview.backgroundColor = MColor;}
傳入一段H5代碼獲取其中所有的img元素的Url
- (NSArray*) getImageurlFromHtml:(NSString*) webString{NSMutableArray* imageurlArray = [NSMutableArrayarrayWithCapacity:1];//標(biāo)簽匹配NSString*parten =@"";NSError* error =NULL;NSRegularExpression*reg = [NSRegularExpressionregularExpressionWithPattern:parten options:0error:&error];NSArray* match = [reg matchesInString:webString options:0range:NSMakeRange(0, [webString length] -1)];for(NSTextCheckingResult* resultinmatch) {//過(guò)去數(shù)組中的標(biāo)簽NSRangerange = [result range];NSString* subString = [webString substringWithRange:range];//從圖片中的標(biāo)簽中提取ImageURLNSRegularExpression*subReg = [NSRegularExpressionregularExpressionWithPattern:@"http://(.*?)\""options:0error:NULL];NSArray* match = [subReg matchesInString:subString options:0range:NSMakeRange(0, [subString length] -1)];NSTextCheckingResult* subRes = match[0];NSRangesubRange = [subRes range];? ? ? ? subRange.length = subRange.length-1;NSString* imagekUrl = [subString substringWithRange:subRange];//將提取出的圖片URL添加到圖片數(shù)組中[imageurlArray addObject:imagekUrl];? ? }returnimageurlArray;}
給label加下劃線,中劃線
NSString*textStr = [NSStringstringWithFormat:@"¥%@", oldPrice];NSDictionary*attribtDic = @{NSStrikethroughStyleAttributeName:? [NSNumbernumberWithInteger:NSUnderlineStyleSingle]};NSMutableAttributedString*attribtStr = [[NSMutableAttributedStringalloc]initWithString:textStr attributes:attribtDic];self.oldPrice_label.attributedText = attribtStr;
利用Quartz2D畫(huà)一張圖片保存到指定位置
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,100),NO,0);CGContextRefctx =UIGraphicsGetCurrentContext();CGContextAddEllipseInRect(ctx,CGRectMake(0,0,100,100));CGContextStrokePath(ctx);UIImage*image=UIGraphicsGetImageFromCurrentImageContext();NSData*data=UIImagePNGRepresentation(image);? [data writeToFile:@"/Users/yy-info/Documents/Practice/imgName.png"atomically:YES];
給UI控件加上虛線框(Quartz2D繪圖)
CGFloatwidth = _label.frame.size.width;CGFloatheight = _label.frame.size.height;CAShapeLayer*shapelayer = [CAShapeLayerlayer];? ? ? ? shapelayer.bounds=CGRectMake(0,0, width, height);? ? ? ? shapelayer.position=CGPointMake(CGRectGetMinX(_label.bounds),CGRectGetMinY(_label.bounds));? ? ? shapelayer.anchorPoint =CGPointMake(0,0);? ? ? ? shapelayer.path= [UIBezierPathbezierPathWithRoundedRect:shapelayer.bounds cornerRadius:5].CGPath;? ? ? ? shapelayer.lineWidth =1;? ? ? ? shapelayer.lineDashPattern=@[@5,@2];? ? ? ? shapelayer.fillColor=nil;? ? ? ? shapelayer.strokeColor= [UIColorcolorWithRed:51/255.0green:51/255.0blue:51/255.0alpha:1].CGColor;? ? ? ? [_label.layer addSublayer:shapelayer];
*CALayer的震動(dòng)
CAKeyframeAnimation*kfa = [CAKeyframeAnimationanimationWithKeyPath:@"transform.translation.x"];CGFloats =16;? ? kfa.values=@[@(-s),@(0),@(s),@(0),@(-s),@(0),@(s),@(0)];//時(shí)長(zhǎng)kfa.duration=.1f;//重復(fù)kfa.repeatCount=9;//移除kfa.removedOnCompletion=YES;? ? [_label.layer addAnimation:kfa forKey:@"shake"];