IOS工具方法
时间方法
/**
* 获得日期对象
*
* @return 日期
*/
+ (NSDateComponents *)getComponents
{
return [[NSCalendar currentCalendar] components:
NSYearCalendarUnit|
NSMonthCalendarUnit|
NSDayCalendarUnit|
NSWeekdayCalendarUnit|
NSWeekOfMonthCalendarUnit fromDate:[NSDate date]];
}
#pragma mark - 根据月份的数字获得中文的月份
+ (NSString *)getMonthByMonthDigtal:(NSInteger)month
{
NSString *monthStr = nil;
switch (month) {
case 1:
monthStr = @"一月";
break;
case 2:
monthStr = @"二月";
break;
case 3:
monthStr = @"三月";
break;
case 4:
monthStr = @"四月";
break;
case 5:
monthStr = @"五月";
break;
case 6:
monthStr = @"六月";
break;
case 7:
monthStr = @"七月";
break;
case 8:
monthStr = @"八月";
break;
case 9:
monthStr = @"九月";
break;
case 10:
monthStr = @"十月";
break;
case 11:
monthStr = @"十一月";
break;
case 12:
monthStr = @"十二月";
break;
default:
break;
}
return monthStr;
}
/**
* 获取每月的最后一天
*
* @param month 月
*
* @return 最后一天
*/
+ (NSInteger)getMonthLastDay:(NSInteger)month
{
NSInteger lastDay = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
lastDay = 31;
break;
case 2:
lastDay = 28;
break;
case 4:
case 6:
case 9:
case 11:
lastDay = 30;
break;
default:
break;
}
return lastDay;
}
/**
* 获得当前月的结束时间
*
* @return 结束时间
*/
+ (long long)getCurrentMonthEndTime
{
NSDateComponents *compnents = [self getComponents];
NSString *timeStr = [NSString stringWithFormat:@"%zd-%zd-%zd 23:59:59",compnents.year,compnents.month,[ETool getMonthLastDay:compnents.month]];
NSDate *timeDate = [EKBTimeFormatter getDateTimeFromDateStr:timeStr];
long long currentTime = [EKBTimeFormatter getDateTimeTOMilliSeconds:timeDate];
return currentTime;
}
/**
* 获得当年的开始时间
*
* @return 当前年的开始时间
*/
+ (long long)getCurrentYearStartTime
{
NSDateComponents *compnents = [self getComponents];
NSString *startStr = [NSString stringWithFormat:@"%zd-01-01 00:00:00",compnents.year];
NSDate *startTime = [EKBTimeFormatter getDateTimeFromDateStr:startStr];
return [EKBTimeFormatter getDateTimeTOMilliSeconds:startTime];
}
电话号码判断
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
/**
* 手机号码
* 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
* 联通:130,131,132,152,155,156,185,186
* 电信:133,1349,153,180,189
*/
NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|7[06-8]|8[025-9])\\d{8}$";
/**
* 中国移动:China Mobile
* 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
*/
NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
/**
* 中国联通:China Unicom
* 130,131,132,152,155,156,185,186
*/
NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
/**
* 中国电信:China Telecom
* 133,1349,153,180,189
*/
NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
/**
* 虚拟运营商
* 中国电信:1700
* 中国联通:1709
* 中国移动:1705
*/
NSString * VNO = @"^1(700|705|709)\\d{7}$";
/**
* 测试用:199开头
*/
NSString *testNu = @"^1(99)\\d{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];
NSPredicate *regextestvno = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", VNO];
NSPredicate *regextestTestNu = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", testNu];
if (([regextestmobile evaluateWithObject:mobileNum] == YES)
|| ([regextestcm evaluateWithObject:mobileNum] == YES)
|| ([regextestct evaluateWithObject:mobileNum] == YES)
|| ([regextestcu evaluateWithObject:mobileNum] == YES)
|| ([regextestvno evaluateWithObject:mobileNum] == YES)
|| ([regextestTestNu evaluateWithObject:mobileNum] == YES))
{
return YES;
}
else
{
return NO;
}
}
数字格式化
* 格式化数字为千位分隔符数字
*
* @param number 要格式化的数字
*
* @return 格式化之后的字符串
*/
+ (NSString *)formatThousandSeparatorFromDigital:(NSNumber *)number
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setPositiveFormat:@"###,##0.00;"];
return [formatter stringFromNumber:number];
}
/**
* 从千位分隔符字符串中获取数字
*
* @param number 千位分隔符字符串
*
* @return 数字
*/
+ (NSNumber *)formatThousandSeparatorFromString:(NSString *)numberString
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setPositiveFormat:@"###,##0.00;"];
return [formatter numberFromString:numberString];
}
邮箱合法性
/**
* 验证邮箱的合法性
*
* @param email 要验证的邮箱
*
* @return 是否是邮箱
*/
+ (BOOL)isValidateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailPredicate evaluateWithObject:email];
}
3DES加密解密算法
- (NSString*)encrypt{
NSData* data = [self dataUsingEncoding:NSUTF8StringEncoding];
size_t plainTextBufferSize = [data length];
const void *vplainText = (const void *)[data bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
const void *vkey = (const void *) [EKBThirdAccountInfo12306PasswordKey UTF8String];
const void *vinitVec = (const void *) [gIv UTF8String];
ccStatus = CCCrypt(kCCEncrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySize3DES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *result = [GTMBase64 stringByEncodingData:myData];
return result;
}
- (NSString*)decrypt
{
NSData *encryptData = [GTMBase64 decodeData:[self dataUsingEncoding:NSUTF8StringEncoding]];
size_t plainTextBufferSize = [encryptData length];
const void *vplainText = [encryptData bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
const void *vkey = (const void *) [EKBThirdAccountInfo12306PasswordKey UTF8String];
const void *vinitVec = (const void *) [gIv UTF8String];
ccStatus = CCCrypt(kCCDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySize3DES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSString *result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding];
return result;
}
字符串宽高算法
- (CGSize)sizeWithFont:(UIFont *)font maxRectSize:(CGSize)maxSize
{
NSDictionary *attributes = @{NSFontAttributeName:font};
return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}
字符串匹配(谓词)传入正则字符串
- (NSString *)firstMatchWithPattern:(NSString *)pattern
{
NSError *error;
NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:&error];
if (error) {
NSLog(@"%@",error.localizedDescription);
return nil;
}
NSTextCheckingResult *result = [regular firstMatchInString:self options:NSRegularExpressionDotMatchesLineSeparators | NSRegularExpressionCaseInsensitive range:NSMakeRange(0, self.length)];
if (result) {
NSRange range = [result rangeAtIndex:1];
return [self substringWithRange:range];
}
return nil;
}
#pragma mark - 匹配多项
- (NSArray *)matchsWithPattern:(NSString *)pattern
{
NSError *error;
NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:&error];
if (error) {
NSLog(@"%@",error.localizedDescription);
return nil;
}
NSArray *array = [regular matchesInString:self options:NSRegularExpressionDotMatchesLineSeparators | NSRegularExpressionCaseInsensitive range:NSMakeRange(0, self.length)];
if ([array count] > 0) {
return array;
}
return nil;
}
#pragma mark 截断收尾空白字符
- (NSString *)trimString
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
图片处理改变尺寸,拉伸位置
+ (UIImage *)resizeWithName:(NSString *)imageName
{
return [self resizeWithName:imageName leftRate:0.5 topRatio:0.5];
}
+ (UIImage *)resizeWithName:(NSString *)imageName leftRate:(CGFloat)leftRate topRatio:(CGFloat)topRatio
{
UIImage *image = [self imageWithName:imageName];
CGFloat left = image.size.width * leftRate;
CGFloat top = image.size.height * topRatio;
return [image stretchableImageWithLeftCapWidth:left topCapHeight:top];
}
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
[image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
- (UIImage *) imageWithTintColor:(UIColor *)tintColor
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
TableViewCell在Nib加载代码重用
@implementation UITableViewCell (Reuse)
+ (instancetype )cellWithTableView:(UITableView *)tableView
{
return [self cellWithTableView:tableView createBlock:nil];
}
+ (instancetype )cellWithTableView:(UITableView *)tableView
createBlock:(UITableViewCell *(^)(NSString *reuseIdentifier))createBlock
{
return [self cellWithTableView:tableView createBlock:createBlock initialBlock:nil];
}
+ (instancetype )cellWithTableView:(UITableView *)tableView
initialBlock:(void(^)(UITableViewCell *))initialBlock
{
return [self cellWithTableView:tableView createBlock:nil initialBlock:initialBlock];
}
+ (instancetype )cellWithTableView:(UITableView *)tableView
createBlock:(UITableViewCell *(^)(NSString *reuseIdentifier))createBlock
initialBlock:(void(^)(UITableViewCell *))initialBlock
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.description];
if (!cell) {
NSString *xibPath = [[NSBundle mainBundle] pathForResource:[self xibName] ofType:@"nib"];
if (xibPath) {
cell = [self createViewFromXibWithOwner:nil];
} else {
if (createBlock) {
cell = createBlock(self.description);
} else {
cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.description];
}
}
if (initialBlock) {
initialBlock(cell);
}
}
return cell;
}
@end
UIView属性处理x, y, width, height,圆角,抖动动画设置
@implementation UIView (Self)
- (void)setX:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)x
{
return self.frame.origin.x;
}
- (void)setY:(CGFloat)y
{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)y
{
return self.frame.origin.y;
}
- (void)setCentreX:(CGFloat)centreX
{
CGPoint center = self.center;
center.x = centreX;
self.center = center;
}
- (CGFloat)centreX
{
return self.center.x;
}
- (void)setCentreY:(CGFloat)centreY
{
CGPoint center = self.center;
center.y = centreY;
self.center = center;
}
- (CGFloat)centreY
{
return self.center.y;
}
- (void)setWidth:(CGFloat)width
{
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)width
{
return self.frame.size.width;
}
- (void)setHeight:(CGFloat)height
{
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (CGFloat)height
{
return self.frame.size.height;
}
- (void)setSize:(CGSize)size
{
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
- (CGSize)size
{
return self.frame.size;
}
#pragma mark - 设置视图圆角
- (void)setCornerOnTop
{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
cornerRadii:CGSizeMake(10.0f, 10.0f)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setCornerOnBottom
{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
cornerRadii:CGSizeMake(10.0f, 10.0f)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setAllCorner
{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
cornerRadius:10.0];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setNoneCorner
{
self.layer.mask = nil;
}
- (void)setCornerOnLeft
{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft)
cornerRadii:CGSizeMake(5.0f, 5.0f)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setCornerOnRight
{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(5.0f, 5.0f)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
-(void)shakeWithtTanslation:(CGFloat)translation
if (translation) {
[self.layer removeAllAnimations];
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
CGFloat currentTx = self.transform.tx;
animation.duration = 0.5;
animation.values = @[ @(currentTx), @(currentTx + translation), @(currentTx-translation*0.5), @(currentTx + translation*0.5), @(currentTx) ];
animation.keyTimes = @[ @(0), @(0.25), @(0.5), @(0.75), @(1) ];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.layer addAnimation:animation forKey:@"shake"];
}
}
@end