iOS開(kāi)發(fā)常用代碼大全

感謝作者: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"];

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末盛杰,一起剝皮案震驚了整個(gè)濱河市挽荡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌即供,老刑警劉巖定拟,帶你破解...
    沈念sama閱讀 211,423評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異逗嫡,居然都是意外死亡青自,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,147評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門驱证,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)延窜,“玉大人,你說(shuō)我怎么就攤上這事抹锄∧嫒穑” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,019評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵伙单,是天一觀的道長(zhǎng)呆万。 經(jīng)常有香客問(wèn)我,道長(zhǎng)车份,這世上最難降的妖魔是什么谋减? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,443評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮扫沼,結(jié)果婚禮上出爹,老公的妹妹穿的比我還像新娘。我一直安慰自己缎除,他們只是感情好严就,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,535評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著器罐,像睡著了一般梢为。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,798評(píng)論 1 290
  • 那天铸董,我揣著相機(jī)與錄音祟印,去河邊找鬼。 笑死粟害,一個(gè)胖子當(dāng)著我的面吹牛蕴忆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播悲幅,決...
    沈念sama閱讀 38,941評(píng)論 3 407
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼套鹅,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了汰具?” 一聲冷哼從身側(cè)響起卓鹿,我...
    開(kāi)封第一講書(shū)人閱讀 37,704評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎留荔,沒(méi)想到半個(gè)月后减牺,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,152評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡存谎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,494評(píng)論 2 327
  • 正文 我和宋清朗相戀三年拔疚,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片既荚。...
    茶點(diǎn)故事閱讀 38,629評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡稚失,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出恰聘,到底是詐尸還是另有隱情句各,我是刑警寧澤,帶...
    沈念sama閱讀 34,295評(píng)論 4 329
  • 正文 年R本政府宣布晴叨,位于F島的核電站凿宾,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏兼蕊。R本人自食惡果不足惜初厚,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,901評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望孙技。 院中可真熱鬧产禾,春花似錦、人聲如沸牵啦。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,742評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)哈雏。三九已至楞件,卻和暖如春衫生,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背土浸。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,978評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工罪针, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人栅迄。 一個(gè)月前我還...
    沈念sama閱讀 46,333評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像皆怕,于是被迫代替她去往敵國(guó)和親毅舆。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,499評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容