前言
没有其他巴拉巴拉的一堆,直接上干货,分享自己从事iOS开发以来积累的Category工具类别,提高大家的开发效率!
PS:我会不定期进行更新,加入一些新的方法;
2020.5.30更新
1.增加NSDate类一些常用的转换方法;
2.增加快速创建富文本字符串的方法;
3.优化了字典转字符串方法, 处理了转出来的字符串带/n和空格的情况;
4.NSString+Safe增加了stringWithFormat避免显示null的方法;
2018.5.22更新
1.优化了千分符方法;
2.将各个健壮性方法单独提取出来;
3.优化了覆盖及拦截method;
2017.8.25更新
1.进行了局部的重新排版;
2.添加了NSObject的一些分类方法(具体见下面内容);
3.合并了一些类目方法;
4.整理了整个项目文件夹,条目更加清晰;
5.添加了更多的注释;
这边我给大家分享的基本都是常用类,其中包括NSObject、 NSString、 NSArray、NSDictionary、UIView、UIImage、UIButton、UIView、UIView、NSData、UIMenuItem、NSDate。
以下一个个来进行概要说明:
NSString && NSAttributedString
NSString 部分包括:
1.一些在项目中常用的方法
/// 字典转Json字符串,处理了/n和空格
/// @param dic
+ (NSString *) dicTransToJSONStringWith:(NSDictionary *)dic;
//电话号码中间4位*显示
+ (NSString*) getSecrectStringWithPhoneNumber:(NSString*)phoneNum;
//银行卡号中间8位*显示
+ (NSString*) getSecrectStringWithAccountNo:(NSString*)accountNo;
//转为手机格式,默认为-
+ (NSString*) stringMobileFormat:(NSString*)mobile;
//金额数字添加单位(暂时写了万和亿,有更多的需求请参考写法来自行添加)
+ (NSString*) stringChineseFormat:(double)value;
//添加数字的千位符
+ (NSString*) countNumAndChangeformat:(NSString *)num;
// NSString转为NSNumber
- (NSNumber*) toNumber;
//计算文字高度
- (CGFloat ) heightWithFontSize:(CGFloat)fontSize width:(CGFloat)width;
//计算文字宽度
- (CGFloat ) widthWithFontSize:(CGFloat)fontSize height:(CGFloat)maxHeight;
//抹除小数末尾的0
- (NSString*) removeUnwantedZero;
//去掉前后空格
- (NSString*) trimmedString;
2.常用的正则表达式判断
//有效的电话号码
- (BOOL) isValidMobileNumber;
//有效的真实姓名
- (BOOL) isValidRealName;
//是否只有中文
- (BOOL) isOnlyChinese;
//有效的验证码(根据自家的验证码位数进行修改)
- (BOOL) isValidVerifyCode;
//有效的银行卡号
- (BOOL) isValidBankCardNumber;
//有效的邮箱
- (BOOL) isValidEmail;
//有效的字母数字密码
- (BOOL) isValidAlphaNumberPassword;
//检测有效身份证
//15位
- (BOOL) isValidIdentifyFifteen;
//18位
- (BOOL) isValidIdentifyEighteen;
//限制只能输入数字
- (BOOL) isOnlyNumber;
3.从时间戳转为显示时间(几小时前等)
//通过时间戳计算时间差(几小时前、几天前)
+ (NSString *) compareCurrentTime:(NSTimeInterval) compareDate;
//通过时间戳得出显示时间
+ (NSString *) getDateStringWithTimestamp:(NSTimeInterval)timestamp;
//通过时间戳和格式显示时间
+ (NSString *) getStringWithTimestamp:(NSTimeInterval)timestamp formatter:(NSString*)formatter;
4.提高NSString && NSMutableString 健壮性的写法(建议各位平时操作NSString及NSMutableString尽量使用,减少闪退)
NSString:
//避免Format所得的字符串带有null
+ (instancetype)noNULLStringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
- (NSString *)safeSubstringFromIndex:(NSUInteger)from;
- (NSString *)safeSubstringToIndex:(NSUInteger)to;
- (NSString *)safeSubstringWithRange:(NSRange)range;
- (NSRange)safeRangeOfString:(NSString *)aString;
- (NSRange)safeRangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
- (NSString *)safeStringByAppendingString:(NSString *)aString;
NSMutableString:
- (void)safeInsertString:(NSString *)aString atIndex:(NSUInteger)loc;
- (void)safeAppendString:(NSString *)aString;
- (void)safeSetString:(NSString *)aString;
NSAttributedString部分:
// 快速创建富文本字符串,包含了Str 颜色 字体 字体间距 行间距 range
+ (NSAttributedString *)attributedWithString:(NSString *)string
font:(UIFont*)font
color:(UIColor *)color;
+ (NSAttributedString *)attributedWithString:(NSString *)string
font:(UIFont*)font
color:(UIColor *)color
wordSpacing:(CGFloat)wordSpacing
lineSpacing:(CGFloat)lineSpacing;
+ (NSAttributedString *)attributedWithString:(NSString *)string
font:(UIFont*)font
color:(UIColor *)color
wordSpacing:(CGFloat)wordSpacing
lineSpacing:(CGFloat)lineSpacing
range:(NSRange)range;
//html片段转为富文本放在Label、Button上显示,这样HTML标签才会生效
+ (NSAttributedString*)htmlToAttString:(NSString*)string;
//由于系统计算富文本的高度不正确,自己写了方法
- (CGFloat)heightWithContainWidth:(CGFloat)width;
NSArray && NSDictionary
这两个大类的分类主要是提升健壮性(建议各位平时操作NSString及NSMutableString尽量使用,减少闪退)以及转为json字符串
NSArray、NSMutableArray:
@interface NSArray (Safe)
//以下写法均防止闪退
+ (instancetype)safeArrayWithObject:(id)object;
- (id)safeObjectAtIndex:(NSUInteger)index;
- (NSArray *)safeSubarrayWithRange:(NSRange)range;
- (NSUInteger)safeIndexOfObject:(id)anObject;
@end
@interface NSMutableArray (Safe)
//以下写法均防止闪退
- (void)safeAddObject:(id)object;
- (void)safeInsertObject:(id)object atIndex:(NSUInteger)index;
- (void)safeInsertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexs;
- (void)safeRemoveObjectAtIndex:(NSUInteger)index;
- (void)safeRemoveObjectsInRange:(NSRange)range;
@end
NSDictionary、NSMutableDictionary
@interface NSDictionary (Safe)
//用于数据解析,返回对象为字符串或值类型,数组和字典不要用此方法
- (id)safeObjectForKey:(NSString *)key;
//设置键值对 针对对象为空处理
- (void)safeSetObject:(id)object forKey:(id)key;
- (id)objectForKeyCustom:(id)aKey;
- (id)safeKeyForValue:(id)value;
@end
@interface NSMutableDictionary (Safe)
- (void)safeSetObject:(id)aObj forKey:(id<NSCopying>)aKey;
- (id)safeObjectForKey:(id<NSCopying>)aKey;
@end
NSObject
NSObject部分包括:
1.为当前object动态增加属性
@property (nonatomic, strong, readonly) NSMutableArray *associatedObjectNames;
//为当前object动态增加分类
- (void)objc_setAssociatedObject:(NSString *)propertyName value:(id)value policy:(objc_AssociationPolicy)policy;
//获取当前object某个动态增加的分类
- (id)objc_getAssociatedObject:(NSString *)propertyName;
//删除动态增加的所有分类
- (void)objc_removeAssociatedObjects;
//获取对象的所有属性
- (NSArray *)getProperties;
2.dispatch主线程和非主线程的快捷写法
// try catch
+ (NSException *)tryCatch:(void(^)())block;
+ (NSException *)tryCatch:(void(^)())block finally:(void(^)())aFinisheBlock;
// 在主线程运行block
+ (void)performInMainThreadBlock:(void(^)())aInMainBlock;
//延时在主线程运行block
+ (void)performInMainThreadBlock:(void(^)())aInMainBlock afterSecond:(NSTimeInterval)delay;
//在非主线程运行block
+ (void)performInThreadBlock:(void(^)())aInThreadBlock;
//延时在非主线程运行block
+ (void)performInThreadBlock:(void(^)())aInThreadBlock afterSecond:(NSTimeInterval)delay;
3.Runtime 覆盖方法、交换方法
+ (BOOL)overrideMethod:(SEL)origSel withMethod:(SEL)altSel;
+ (BOOL)overrideClassMethod:(SEL)origSel withClassMethod:(SEL)altSel;
+ (BOOL)exchangeMethod:(SEL)origSel withMethod:(SEL)altSel;
+ (BOOL)exchangeClassMethod:(SEL)origSel withClassMethod:(SEL)altSel;
UIView && UIImage && UIButton && UIColor
UIView:
@interface UIView (Category)
//把View加在Window上
- (void) addToWindow;
@end
@interface UIView (Screenshot)
//View截图
- (UIImage*) screenshot;
//ScrollView截图 contentOffset
- (UIImage*) screenshotForScrollViewWithContentOffset:(CGPoint)contentOffset;
//View按Rect截图
- (UIImage*) screenshotInFrame:(CGRect)frame;
@end
@interface UIView (Animation)
//左右抖动动画
- (void) shakeAnimation;
//旋转180度
- (void) trans180DegreeAnimation;
@end
UIImage:这里内容很多我只列出一部分,具体的大家可以down或者clone下来之后仔细看
//由颜色生成图片
+ (UIImage *) imageWithColor:(UIColor*)color;
//将图片剪裁至目标尺寸
+ (UIImage *) imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize;
//图片旋转角度
- (UIImage *) imageRotatedByDegrees:(CGFloat)degrees;
//拉伸图片UIEdgeInsets
- (UIImage *) resizableImage:(UIEdgeInsets)insets;
//拉伸图片CGFloat
- (UIImage *) imageByResizeToScale:(CGFloat)scale;
//放大图片CGSize
- (UIImage *) imageByResizeWithMaxSize:(CGSize)size;
//小样图图片CGSize
- (UIImage *) imageWithThumbnailForSize:(CGSize)size;
//通过Rect剪裁图片
- (UIImage *) imageByCropToRect:(CGRect)rect;
UIButton:非常推荐大家使用扩大点击范围的方法(非常实用)
//扩大点击范围,实用性非常强的一个方法,极力推荐
- (void)setEnlargeEdgeWithTop:(CGFloat)top right:(CGFloat)right bottom:(CGFloat)bottom left:(CGFloat)left;
//快速添加按钮响应方法,默认为TouchUpInside
- (void)addCallBackAction:(ButtonActionCallBack)action;
//快速添加按钮响应方法
- (void)addCallBackAction:(ButtonActionCallBack)action
forControlEvents:(UIControlEvents)controlEvents;
UIColor:rgb、二进制、十六进制转换
//功能:通过RGB创建颜色
UIColor *rgb(CGFloat red, CGFloat green, CGFloat blue);
//功能:通过RGB以及alpha创建颜色
UIColor *rgbA(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha);
@interface UIColor (Category)
// Create a color from a HEX string.
+ (UIColor *)hex:(NSString *)hexString;
//通过0xffffff的16进制数字创建颜色
+ (UIColor *)colorWithRGB:(NSUInteger)aRGB;
//调节颜色的明亮度
+ (UIColor*) colorRGBonvertToHSB:(UIColor*)color withBrighnessDelta:(CGFloat)delta;
//调整颜色的透明度
+ (UIColor*) colorRGBonvertToHSB:(UIColor*)color withAlphaDelta:(CGFloat)delta;
@end
NSDate:日期转换
@interface NSDate (Category)
#pragma mark - 返回NSString部分
/// NSDate转格式显示
/// @param date 例如:[NSDate date]
/// @param formatter @"yyyy-MM-dd"
+ (NSString *)dateToString:(NSDate *)date dateFormatter:(NSString *)formatter;
/// 时间戳转格式显示
/// @param timeInterval
/// @param formatter @"yyyy-MM-dd"
+ (NSString *)timeIntervalToString:(NSTimeInterval)timeInterval dateFormatter:(NSString *)formatter;
#pragma mark - 返回NSDate部分
/// 根据显示时间的字符串返回NSDate
/// @param timeString 例如:1980-01-01
/// @param format @"yyyy-MM-dd"
+ (NSDate *)dateWithDateString:(NSString *)timeString formatString:(NSString *)format;
/// 在已有NSDate的情况下,加减具体数字的年月日,获取未来或者过去的NSDate
/// @param presentDate
/// @param year 小于0为过去,大于0则为未来
/// @param month
/// @param day
+ (NSDate *)dateWithPresentDate:(NSDate*)presentDate year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
/// 根据具体的年月日获取NSDate
/// @param year
/// @param month
/// @param day
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
#pragma mark - 返回整型部分
/// 根据前后NSDate,获取中间差了多少天
/// @param startDate 开始时间
/// @param endDate 结束时间
+ (NSInteger)daysBetweenStartDate:(NSDate *)startDate endDate:(NSDate *)endDate;
/// 获取传入Date对应的月份有多少天
/// @param date
+ (NSInteger)totaldaysInMonth:(NSDate *)date;
// 是否和当前同一天
+ (BOOL)isCurrentDay:(NSDate *)date;
@end
结语
这边把一些常用的工具类别分享给了大家,基本每个方法都是我在实际项目因为某些需求写的、还有部分是网上找的。如果不会使用可以来询问我,发现错误请及时联系我,不喜勿喷,谢谢~
PS:各位请自行选择需要的添加的类~
以后我还会持续更新的!最后放出传送门。。麻烦下载的同学给点个星或者点个赞 ,谢谢啦!