iOS开发常用代码大全

感谢作者:Arackboss

原文链接:https://www.jianshu.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;}

身份证号码验证

#pragma mark -身份证号全校验+ (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)];// 判断校验位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;

}

压缩图片

/**

*  实现图片的缩小或者放大

*

*  @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;//返回的就是已经改变的图片}

让网络加载图片有个动画效果(前提是导入了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;        }    }];}

根据字符串的长度计算高度

+ (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;    }

拼接属性字符串,在电商类应用用的比较多(比如价格,市场价和销售价,此时可以用一个lable搞定,而不用两个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;}

调整label行间距

NSMutableAttributedString*attributedString = [[NSMutableAttributedStringalloc] initWithString:string];NSMutableParagraphStyle*paragraphStyle = [[NSMutableParagraphStylealloc] init];    paragraphStyle.lineSpacing = lineSpace;// 调整行间距NSRangerange =NSMakeRange(0, [string length]);    [attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:range];returnattributedString;}

创建导航栏按钮

+ (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];}

数组的安全操作

- (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]);}

获取当前时间

-(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"]; }

比较两个时间的大小

-(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;}

日期格式转字符串

//日期格式转字符串- (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;}

字符串转日期格式

- (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;}

将世界时间转化为中国区时间

- (NSDate*)worldTimeToChinaTime:(NSDate*)date{NSTimeZone*timeZone = [NSTimeZonesystemTimeZone];NSIntegerinterval = [timeZone secondsFromGMTForDate:date];NSDate*localeDate = [date  dateByAddingTimeInterval:interval];returnlocaleDate;}

传入今天的时间,返回明天的时间

//传入今天的时间,返回明天的时间- (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]) {//取项目的bundleIdentifier作为KEY  改动了此处//NSString *key = [[NSBundle mainBundle] bundleIdentifier];NSData*data = [text dataUsingEncoding:NSUTF8StringEncoding];//IOS 自带DES加密 Begin  改动了此处//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]) {//取项目的bundleIdentifier作为KEY  改动了此处//NSString *key = [[NSBundle mainBundle] bundleIdentifier];NSData*data = [selfdataWithBase64EncodedString:base64];//IOS 自带DES解密 Begin    改动了此处//data = [self DESDecrypt:data WithKey:key];//IOS 自带DES加密 Endreturn[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];    }else{returnLocalStr_None;    }}

字符串反转

**字符串反转**//第一种:- (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];

将十六进制颜色转换为 UIColor 对象

+ (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中某个区域生成一张图片

+ (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添加生成圆角图片的扩展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;  }//然后调用时就直接传一个圆角来处理:  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(数据帧率),并且离屏需要创建新的缓冲区和上下文切换,因此消耗较大的性能。

删除缓存

- (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];          }      }  }

计算清除的缓存大小

- (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);  }

计算单个文件大小

- (longlong)fileSizeAtPath:(NSString*)file  {NSFileManager*man = [NSFileManagerdefaultManager];if([man fileExistsAtPath:file]) {return[[man attributesOfItemAtPath:file error:nil] fileSize];      }return0;  }

通过视图,寻找父控制器

- (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选中后其子视图颜色会改变,重写下面两个方法可以避免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];//标签匹配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) {//过去数组中的标签NSRangerange = [result range];NSString* subString = [webString substringWithRange:range];//从图片中的标签中提取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添加到图片数组中[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画一张图片保存到指定位置

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的震动

CAKeyframeAnimation*kfa = [CAKeyframeAnimationanimationWithKeyPath:@"transform.translation.x"];CGFloats =16;    kfa.values=@[@(-s),@(0),@(s),@(0),@(-s),@(0),@(s),@(0)];//时长kfa.duration=.1f;//重复kfa.repeatCount=9;//移除kfa.removedOnCompletion=YES;    [_label.layer addAnimation:kfa forKey:@"shake"];

你可能感兴趣的:(iOS开发常用代码大全)