作为程序员,我想每个人在开发之前都喜欢封装一些简单的方法,加快自己开发的速度,我分享一些的�用到过得,不是什么高深的玩意,不是大牛,并没有装逼的技能,直接上代码,我一般都会建一个方法类
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Methods : NSObject
//获取Storyboard上面的视图控制器
+ (UIViewController *)getVCWithIdentifier:(NSString *)theIdentifier andStoryboardName:(NSString *)theName;
/** 通过颜色来生成一个纯色图片 */
+ (UIImage *)imageFromColor:(UIColor *)color andCGRect:(CGRect)rect;
/*返回按钮*/
+ (void)setNavBarBack:(UIViewController *)theVC;
/*跳转视图控制器*/
+(void)push:(UIViewController *)theVC To:(UIViewController *)VC;
//移除数据
+ (void)removeUserInfoObject;
/** 保存数据 */
+ (void)saveAppInfo:(id) obj forKey:(NSString*) key;
/** 读取数据 */
+ (id)readAppInfoForKey:(NSString*) key;
//压缩图片
+ (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize;
/*设置边界*/
+(void)setBorder:(UIView *)theView andFloat:(float)theFloat andColor:(UIColor *)theColor;
/*调整图片角度,针对拍照对图片倾斜90是*/
+ (UIImage *)turnImageWithInfo:(NSDictionary<NSString *,id> *)info;
/*判断字符串为空*/
+ (BOOL)isEmptyWithString:(NSString *)string;
+ (NSString *)getImageURL:(NSString *)String;
+ (NSString *)toString:(id)anyObject;
/*自定义提示效果*/
+(void)showToast:(NSString *)theMsg andTime:(float)theTime;
/* 按钮倒计时*/
+ (void)openCountdown:(UIButton *)authCodeBtn;
/*截屏*/
+ (UIImage *)captureScreen ;
/*限制输入*/
+ (BOOL)validateChar:(NSString*)charStr andLimit:(NSString *)limitStr;
/**/
+ (CGSize)getAutoHeight:(NSString *)testStr andFontOfSize:(int)Size andExtrawidth:(float)width;
/*
*功能说明:
* 为了避免从网络上得到不是预期的字段而使得后续处理出现问题,而做的一个过滤
*参数说明:
*string : 需要过滤处理的字符串并去掉多余的空格等
*defaultString : 不符合条件时的默认字符串
*/
+ (NSString *)getString:(NSString *)string withDefault:(NSString *)defaultString;
/* 为了避免从网络上得到不是预期的字段而使得后续处理出现问题,而做的一个过滤*/
+ (NSString *)getStringWithClear:(NSString *)string withDefault:(NSString *)defaultString;
+ (NSString *)clearExtraEntrtKey:(NSString *)string;
/**
* 对应格式的表示时间的字符串转化为时间戳
* 这里的格式是:YYYY-MM-dd HH:mm:ss
* @param str
*
* @return
*/
+ (NSString *) getTimeFromString :(NSString *) str;
/**
* js的文字html化,防止在显示网页内容时出现乱码现象
*/
+ (NSString *)htmlEntityDecode: (NSString *)str;
@end
目前我只收录了这些方法
#import "Methods.h"
@implementation Methods
+ (UIViewController *)getVCWithIdentifier:(NSString *)theIdentifier andStoryboardName:(NSString *)theName {
UIStoryboard *lStoryboard = [UIStoryboard storyboardWithName:theName bundle:[NSBundle mainBundle]];
return [lStoryboard instantiateViewControllerWithIdentifier:theIdentifier];
}
//通过颜色来生成一个纯色图片
+ (UIImage *)imageFromColor:(UIColor *)color andCGRect:(CGRect)rect {
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
+ (void)setNavBarBack:(UIViewController *)theVC {
theVC.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_fanhui"] style:UIBarButtonItemStylePlain target:theVC action:@selector(back:)];
theVC.navigationItem.leftBarButtonItem.imageInsets=UIEdgeInsetsMake(0, -4, 0, 4);
}
- (void)back:(UIBarButtonItem *)item {
}
+(void)push:(UIViewController *)theVC To:(UIViewController *)VC{
[theVC.navigationController pushViewController:VC animated:YES];
}
/*
*功能说明:
* 判断字符串为空
*参数说明:
*string : 需要判断的字符串
*/
#pragma mark - 移除用户信息
+ (void)removeUserInfoObject {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLoggedIn"];
// [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"TOKEN"];
// [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UID"];
}
#pragma mark - 保存数据
+ (void)saveAppInfo:(id) obj forKey:(NSString*) key {
[[NSUserDefaults standardUserDefaults] setObject:obj forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - 读取数据
+ (id)readAppInfoForKey:(NSString*) key {
return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
#pragma mark - 压缩图片
+ (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize
{
//先调整分辨率
CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
CGFloat tempHeight = newSize.height / 1024;
CGFloat tempWidth = newSize.width / 1024;
if (tempWidth > 1.0 && tempWidth > tempHeight) {
newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
}
else if (tempHeight > 1.0 && tempWidth < tempHeight){
newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
}
UIGraphicsBeginImageContext(newSize);
[source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//调整大小
NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
NSUInteger sizeOrigin = [imageData length];
NSUInteger sizeOriginKB = sizeOrigin / 1024;
if (sizeOriginKB > maxSize) {
NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50);
return finallImageData;
}
return imageData;
}
+(void)setBorder:(UIView *)theView andFloat:(float)theFloat andColor:(UIColor *)theColor{
theView.layer.borderColor = theColor.CGColor;
theView.layer.borderWidth = theFloat;
[theView.layer setMasksToBounds:YES];
}
//调整图片角度
+ (UIImage *)turnImageWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
//类型为 UIImagePickerControllerOriginalImage 时调整图片角度
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:@"public.image"]) {
UIImageOrientation imageOrientation=image.imageOrientation;
if(imageOrientation!=UIImageOrientationUp) {
// 原始图片可以根据照相时的角度来显示,但 UIImage无法判定,于是出现获取的图片会向左转90度的现象。
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
return image;
}
/*
*功能说明:
* 为了避免从网络上得到不是预期的字段而使得后续处理出现问题,而做的一个过滤
*参数说明:
*string : 需要过滤处理的字符串并去掉多余的空格等
*defaultString : 不符合条件时的默认字符串
*/
+ (NSString *)getString:(NSString *)string withDefault:(NSString *)defaultString{
NSString * temStr;
if (![string isKindOfClass:[NSString class]]) {
temStr = [Methods toString:string];
}else{
temStr = string;
}
if([Methods isEmptyWithString:temStr]
){
//为空,返回默认数据
return defaultString;
}else{
//不为空,直接返回数据
return temStr;
}
}
/*
*功能说明:
* 为了避免从网络上得到不是预期的字段而使得后续处理出现问题,而做的一个过滤
*参数说明:
*string : 需要过滤处理的字符串
*defaultString : 不符合条件时的默认字符串
*/
+ (NSString *)getStringWithClear:(NSString *)string withDefault:(NSString *)defaultString{
if([Methods isEmptyWithString:string]
){
//为空,返回默认数据
return defaultString;
}else{
//不为空,直接返回数据
return [self clearExtraEntrtKey:string];
}
}
/*
*功能说明:
* 判断字符串为空
*参数说明:
*string : 需要判断的字符串
*/
+ (BOOL)isEmptyWithString:(NSString *)string{
// NSString *string = [theString stringByReplacingOccurrencesOfString:@" " withString:@""];
return ((string == nil)
||([string isEqual:[NSNull null]])
||([string isEqualToString:@"<null>"])
||([string isEqualToString:@"(null)"])
||([string isEqualToString:@" "])
||([string isEqualToString:@""])
||([string isEqualToString:@""])
||([string isEqualToString:@"(\n)"])
||([string isEqualToString:@"yanyu"])
);
}
+ (NSString *)clearExtraEntrtKey:(NSString *)string{
NSString * mString = nil;
NSString *strtemp = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
mString = [strtemp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return mString;
}
#pragma mark - 获取图片url
+ (NSString *)getImageURL:(NSString *)String {
if ([String containsString:@"http://"]) {
return String;
} else {
return [NSString stringWithFormat:@"http://192.168.7.100/zxgs/%@",String];
}
}
+ (NSString *)toString:(id)anyObject {
return [NSString stringWithFormat:@"%@",anyObject];
}
+(void)showToast:(NSString *)theMsg andTime:(float)theTime{
//内容
UIWindow *window=[[UIApplication sharedApplication] keyWindow];
NSDictionary *attribute = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15.0f]};
CGSize labelSize1= [theMsg boundingRectWithSize:CGSizeMake(280, 5000) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
UILabel * patternLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(45,15, labelSize1.width, labelSize1.height)];
patternLabel1.textAlignment=NSTextAlignmentCenter;
patternLabel1.text = theMsg;
patternLabel1.textColor=[UIColor whiteColor];
patternLabel1.backgroundColor = [UIColor clearColor];
patternLabel1.font = [UIFont fontWithName:@"HelveticaNeue" size:15.0f];
patternLabel1.numberOfLines = 0;//
patternLabel1.lineBreakMode = NSLineBreakByCharWrapping;//
UIImageView *picView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 29, 26)];
picView.image = [UIImage imageNamed:@"pic_renzhengchenggong"];
picView.backgroundColor = [UIColor clearColor];
float heightTS=labelSize1.height+20;
float widthTS=labelSize1.width+20;
UIView *viewTishi=[[UIView alloc]initWithFrame:CGRectMake(0, 0, widthTS+30+10, heightTS+10)];
viewTishi.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:1];
viewTishi.alpha=0.7;
[window addSubview:viewTishi];
[viewTishi.layer setMasksToBounds:YES];
[viewTishi.layer setCornerRadius:5.0];
// viewTishi.alpha=0.7;
[viewTishi addSubview:picView];
[viewTishi addSubview:patternLabel1];
// patternLabel1.center.y = viewTishi.center.y;
[viewTishi setCenter:window.center];
// 延迟N秒执行:
double delayInSeconds = theTime;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[patternLabel1 removeFromSuperview];
[viewTishi removeFromSuperview];
});
}
#pragma mark - 按钮倒计时
+ (void)openCountdown:(UIButton *)authCodeBtn {
__block NSInteger time = 59; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(time <= 0){ //倒计时结束,关闭
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//设置按钮的样式
[authCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
[authCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
authCodeBtn.userInteractionEnabled = YES;
});
}else{
int seconds = time % 60;
dispatch_async(dispatch_get_main_queue(), ^{
//设置按钮显示读秒效果
[authCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
[authCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
authCodeBtn.userInteractionEnabled = NO;
});
time--;
}
});
dispatch_resume(_timer);
}
#pragma mark - 截屏
+ (UIImage *)captureScreen {
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
#pragma mark - 限制输入
+ (BOOL)validateChar:(NSString*)charStr andLimit:(NSString *)limitStr {
BOOL res = YES;
NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:limitStr];
int i = 0;
while (i < charStr.length) {
NSString * string = [charStr substringWithRange:NSMakeRange(i, 1)];
NSRange range = [string rangeOfCharacterFromSet:tmpSet];
if (range.length == 0) {
res = NO;
break;
}
i++;
}
return res;
}
+ (CGSize)getAutoHeight:(NSString *)testStr andFontOfSize:(int)Size andExtrawidth:(float)width{
UIFont * tfont = [UIFont systemFontOfSize:Size];
//高度估计文本大概要显示几行,宽度根据需求自己定义。 MAXFLOAT 可以算出具体要多高
CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width - width,MAXFLOAT);//ZWidth 屏幕宽度
// 获取当前文本的属性
NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
//ios7方法,获取文本需要的size,限制宽度
CGSize actualsize = [testStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:nil].size;
// 更新UILabel的frame
return actualsize;
}
+ (NSString *) getTimeFromString :(NSString *) str{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setTimeZone:timeZone];
NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[str integerValue]];
return [formatter stringFromDate:confromTimesp];
}
+ (NSString *)htmlEntityDecode: (NSString *)str{
str = [str stringByReplacingOccurrencesOfString:@""" withString:@"\""];
str = [str stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
str = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
str = [str stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
str = [str stringByReplacingOccurrencesOfString:@">" withString:@">"];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
return str;
}
@end
有些地方做的不够好或者不简洁,请见谅哈。大家也可以给我提供一些自己开发中常用的方法技巧,在这里多谢各位大神指教。
网友评论