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 *)bufferPtrlength:(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 *)tableViewcreateBlock:(
UITableViewCell *(^)(
NSString *reuseIdentifier))createBlock
{
return [
self cellWithTableView:tableView createBlock:createBlock initialBlock:
nil];
}+ (instancetype )cellWithTableView:(
UITableView *)tableViewinitialBlock:(
void(^)(
UITableViewCell *))initialBlock
{
return [
self cellWithTableView:tableView createBlock:
nil initialBlock:initialBlock];
}+ (instancetype )cellWithTableView:(
UITableView *)tableViewcreateBlock:(
UITableViewCell *(^)(
NSString *reuseIdentifier))createBlockinitialBlock:(
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.boundsbyRoundingCorners:(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.boundsbyRoundingCorners:(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.boundscornerRadius:
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.boundsbyRoundingCorners:(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
總結
以上是生活随笔為你收集整理的IOS工具方法小节的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。