概述
在iOS开发过程中,即使在高逼格的项目都是有一个个基本的控件搭建起来的,虽然基本控件的使用非常简单,但是不积跬步,无以至千里。这里是我平时做项目整理的一些控件的常用方法,没有什么高的技术含量,只为了加强自己的记忆。
@interface UIView (Utils)
@property (nonatomic,assign) CGFloat x;
@property (nonatomic,assign) CGFloat y;
@property (nonatomic,assign) CGFloat centerX;
@property (nonatomic,assign) CGFloat centerY;
@property (nonatomic,assign) CGFloat width;
@property (nonatomic,assign) CGFloat height;
@property (nonatomic,assign) CGSize size;
/**
* 添加阴影效果
* color 颜色
* radius 范围
* opacity 透明度
*/
-(void)drawLayerShadowWithColor:(UIColor*)color Radius:(float) radius Opacity:(float) opacity;
/**
* 添加边框
*/
-(void)drawLayerBorderWithColor:(UIColor*)color Width:(CGFloat) width ;
/**
* 设置圆角
*/
-(void)drawLayerCornerWithRadius:(CGFloat) radius;
/**
* 获取当前正在显示的控制器(由于keyWindow的不同可能获取不正确)
*
* @return 正在显示的控制器
*/
+ (UIViewController *)currentViewController;
/**
* 获取当前正在显示的控制器(无论keyWindow是什么)
*
* @return 正在显示的控制器
*/
+ (UIViewController *)getCurrentViewConrtrollerIgnoreWindowLevel;
/**
* 获取当前显示的View的控制器的根控制器
*
* @return 根控制器
*/
+ (UIViewController *)getCurrentRootViewController;
@end
#import "UIView+Utils.h"
@implementation UIView (Utils)
- (UIViewController *)parentController
{
UIResponder *responder = [self nextResponder];
while (responder) {
if ([responder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)responder;
}
responder = [responder nextResponder];
}
returnnil;
}
+ (UIViewController *)currentViewController
{
//如果是在AlertView上可能获取的keyWindow不是UIWindow(注意)
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
// modal展现方式的底层视图不同
// 取到第一层时,取到的是UITransitionView,通过这个view拿不到控制器
UIView *firstView = [keyWindow.subviews firstObject];
UIView *secondView = [firstView.subviews firstObject];
UIViewController *vc = secondView.parentController;
if ([vc isKindOfClass:[UITabBarController class]])
{
UITabBarController *tab = (UITabBarController *)vc;
if ([tab.selectedViewController isKindOfClass:[UINavigationController class]])
{
UINavigationController *nav = (UINavigationController *)tab.selectedViewController;
return [nav.viewControllers lastObject];
} else
{
return tab.selectedViewController;
}
}
else if ([vc isKindOfClass:[UINavigationController class]]) {
UINavigationController *nav = (UINavigationController *)vc;
return [nav.viewControllers lastObject];
}
else
{
return vc;
}
returnnil;
}
+(UIViewController *)getCurrentViewConrtrollerIgnoreWindowLevel
{
// Try to find the root view controller programmically
// Find the top window (that is not an alert view or other window)
UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
if (topWindow.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(topWindowin windows)
{
if (topWindow.windowLevel == UIWindowLevelNormal)
break;
}
}
// modal展现方式的底层视图不同
// 取到第一层时,取到的是UITransitionView,通过这个view拿不到控制器
UIView *firstView = [topWindow.subviews firstObject];
UIView *secondView = [firstView.subviews firstObject];
UIViewController *vc = secondView.parentController;
if ([vc isKindOfClass:[UITabBarController class]])
{
UITabBarController *tab = (UITabBarController *)vc;
if ([tab.selectedViewController isKindOfClass:[UINavigationController class]])
{
UINavigationController *nav = (UINavigationController *)tab.selectedViewController;
return [nav.viewControllers lastObject];
} else
{
return tab.selectedViewController;
}
}
else if ([vc isKindOfClass:[UINavigationController class]]) {
UINavigationController *nav = (UINavigationController *)vc;
return [nav.viewControllers lastObject];
}
else
{
return vc;
}
returnnil;
}
+ (UIViewController *)getCurrentRootViewController
{
UIViewController *result;
// Try to find the root view controller programmically
// Find the top window (that is not an alert view or other window)
UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
if (topWindow.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(topWindowin windows)
{
if (topWindow.windowLevel == UIWindowLevelNormal)
break;
}
}
UIView *rootView = [[topWindow subviews] objectAtIndex:0];
id nextResponder = [rootView nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
result = nextResponder;
else if ([topWindow respondsToSelector:@selector(rootViewController)] && topWindow.rootViewController !=nil)
result = topWindow.rootViewController;
else
NSAssert(NO,@"ShareKit: Could not find a root view controller. You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");
return result;
}
/****------> UIView +Layer <------ ****/
-(void)drawLayerShadowWithColor:(UIColor*)color Radius:(float) radius Opacity:(float) opacity
{
self.layer.shadowOpacity = opacity;//阴影透明度
self.layer.shadowColor = color.CGColor;//阴影的颜色
self.layer.shadowRadius = radius;//阴影扩散的范围控制
self.layer.shadowOffset = CGSizeMake(1,1);//阴影的范围
}
-(void)drawLayerBorderWithColor:(UIColor*)color Width:(CGFloat) width
{
self.layer.borderColor = color.CGColor;//边框颜色
self.layer.borderWidth = width;//边框宽度
}
-(void)drawLayerCornerWithRadius:(CGFloat) radius
{
self.layer.masksToBounds =YES;
self.layer.cornerRadius = radius;
}
/****------> UIView +Frame <------ ****/
- (void)setX:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)x
{
returnself.frame.origin.x;
}
- (void)setY:(CGFloat)y
{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)y
{
returnself.frame.origin.y;
}
- (void)setCenterX:(CGFloat)centerX
{
CGPoint center = self.center;
center.x = centerX;
self.center = center;
}
- (CGFloat)centerX
{
returnself.center.x;
}
- (void)setCenterY:(CGFloat)centerY
{
CGPoint center = self.center;
center.y = centerY;
self.center = center;
}
- (CGFloat)centerY
{
returnself.center.y;
}
- (void)setWidth:(CGFloat)width
{
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)width
{
returnself.frame.size.width;
}
- (void)setHeight:(CGFloat)height
{
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (CGFloat)height
{
returnself.frame.size.height;
}
- (void)setSize:(CGSize)size
{
// self.width = size.width;
// self.height = size.height;
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
- (CGSize)size
{
returnself.frame.size;
}
@end
#import <UIKit/UIKit.h>
@interface UILabel (Utils)
@property (nonatomic,assign)BOOL isCopyable;
- (void)setTextFont:(UIFont *)font atRange:(NSRange)range;
- (void)setTextColor:(UIColor *)color atRange:(NSRange)range;
- (void)setTextLineSpace:(float)space atRange:(NSRange)range;
- (void)setTextFont:(UIFont *)font color:(UIColor *)color atRange:(NSRange)range;
- (void)setTextAttributes:(NSDictionary *)attributes atRange:(NSRange)range;
@end
#import "UILabel+Utils.h"
#import <objc/runtime.h>
@implementation UILabel (Utils)
/*>>>>>>>>>>>>>>>>>>>>>>>>>>Label.attributedText<<<<<<<<<<<<<<<<<<<<<<<<*/
- (void)setTextFont:(UIFont *)font atRange:(NSRange)range
{
[self setTextAttributes:@{NSFontAttributeName : font}
atRange:range];
}
- (void)setTextColor:(UIColor *)color atRange:(NSRange)range
{
[self setTextAttributes:@{NSForegroundColorAttributeName : color}
atRange:range];
}
- (void)setTextLineSpace:(float)space atRange:(NSRange)range
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:space];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
self.attributedText = attributedString;
[self sizeToFit];
}
- (void)setTextFont:(UIFont *)font color:(UIColor *)color atRange:(NSRange)range
{
[self setTextAttributes:@{NSFontAttributeName : font,
NSForegroundColorAttributeName : color}
atRange:range];
}
- (void)setTextAttributes:(NSDictionary *)attributes atRange:(NSRange)range
{
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
for (NSString *namein attributes)
{
[mutableAttributedString addAttribute:name value:[attributes objectForKey:name] range:range];
}
// [mutableAttributedString setAttributes:attributes range:range]; error
self.attributedText = mutableAttributedString;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>Label.attributedText<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>Copy 长按Label可复制文字<<<<<<<<<<<<<<<<<<<<<<<<*/
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return (action ==@selector(copyText:));
}
- (void)attachTapHandler {
self.userInteractionEnabled =YES;
UILongPressGestureRecognizer *g = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:g];
}
// 处理手势相应事件
- (void)handleTap:(UIGestureRecognizer *)g {
[self becomeFirstResponder];
UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyText:)];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:item]];
[[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}
// 复制时执行的方法
- (void)copyText:(id)sender {
// 通用的粘贴板
UIPasteboard *pBoard = [UIPasteboard generalPasteboard];
// 有些时候只想取UILabel的text中的一部分
if (objc_getAssociatedObject(self,@"expectedText")) {
pBoard.string = objc_getAssociatedObject(self,@"expectedText");
} else {
// 因为有时候 label中设置的是attributedText
// 而 UIPasteboard的string只能接受 NSString类型
// 所以要做相应的判断
if (self.text) {
pBoard.string = self.text;
} else {
pBoard.string = self.attributedText.string;
}
}
}
- (BOOL)canBecomeFirstResponder {
return [objc_getAssociatedObject(self,@selector(isCopyable)) boolValue];
}
- (void)setIsCopyable:(BOOL)number {
objc_setAssociatedObject(self,@selector(isCopyable), [NSNumber numberWithBool:number], OBJC_ASSOCIATION_ASSIGN);
[self attachTapHandler];
}
- (BOOL)isCopyable {
return [objc_getAssociatedObject(self,@selector(isCopyable)) boolValue];
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>Copy 长按Label可复制文字<<<<<<<<<<<<<<<<<<<<<<<<*/
@end
#import <UIKit/UIKit.h>
@interface UIButton (Utils)
//以下2个方法,须在设置图片和标题之后使用
/**
* 将按钮转换为竖直样式:图片在上,标题在下
*/
- (void)transToVertical;
/**
* 将按钮转换为竖直样式:图片在上,标题在下
*
* @param padding 图片与标题间距
*/
- (void)transToVerticalWithPadding:(CGFloat)padding;
/**
* 点击按钮伸缩动画
*/
-(void)pressesButtonWithAnimation ;
@end
#import "UIButton+Utils.h"
@implementation UIButton (Utils)
- (void)transToVerticalWithPadding:(CGFloat)padding {
// get the size of the elements here for readability
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;
// get the height they will take up as a unit
CGFloat totalHeight = (imageSize.height + titleSize.height + padding);
// raise the image and push it right to center it
self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height),0.0,0.0, - titleSize.width);
// lower the text and push it left to center it
self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);
}
- (void)transToVertical {
return [self transToVerticalWithPadding:3.0f];
}
-(void)pressesButtonWithAnimation
{
[UIView animateWithDuration:0.2 animations:^{
self.transform = CGAffineTransformMakeScale(0.5,0.5);
}];
[UIView animateWithDuration:0.3 animations:^{
self.transform = CGAffineTransformMakeScale(1.0,1.0);
}];
[UIView animateWithDuration:0.3 animations:^{
self.transform = CGAffineTransformMakeScale(1.5,1.5);
}];
[UIView animateWithDuration:0.2 animations:^{
self.transform = CGAffineTransformMakeScale(1.0,1.0);
}];
}
@end
#import <UIKit/UIKit.h>
@interface UIImage (Utils)
/**
* 判断是否亮色
*
* @return 返回是否亮色
*/
- (BOOL)isLightColor;
/**
* 获得主要颜色
*
* @return 返回主要颜色
*/
- (UIColor *)mostColor;
/**
* 获得颜色RGB值
*
* @param color 颜色
*
* @return 返回颜色RGB值
*/
- (NSArray *)RGBComponentsWithColor:(UIColor *)color;
/**
* 获得缩略图
*
* @param size 缩略图大小
*
* @return 缩略图
*/
- (UIImage *)scaleToSize:(CGSize)size;
//原始图片
+ (instancetype)imageWithOriginName:(NSString *)imageName;
/**
* 根据颜色创建图片
*
* @param color 图片颜色
*
* @return 图片
*/
+ (UIImage *)imageWithColor:(UIColor *)color;
/**
* 截取图片
*
* @param rect 位置、大小
*
* @return 图片
*/
- (UIImage *)trimWithRect:(CGRect)rect;
/**
* 获得旋转后的图片
*
* @param imageName 图片名
* @param orientation 旋转方向
*
* @return 旋转后图片
*/
+ (UIImage *)rotateImageWithImageName:(NSString *)imageName orientation:(UIImageOrientation)orientation;
/**
* 返回一张自由拉伸的图片
*/
+ (UIImage *)resizedImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top;
/**
* 返回一张自由拉伸的图片 left 0.5 top 0.5
*/
+ (UIImage *)resizedImageWithName:(NSString *)name;
/**
* 改变图片的颜色
*/
+(UIImage *)colorizeImage:(UIImage *)baseImage withColor:(UIColor *)theColor;
/**
* 改变图片的背景色
*/
+(UIImage *)colorizeImage:(UIImage *)baseImage withBackgroundColor:(UIColor *)theColor;
/**
* 给图片添加蒙版效果
*
**/
+(UIImage *)maskImage:(UIImage *)baseImage withImage:(UIImage *)theMaskImage;
@end
#import "UIImage+Utils.h"
#import <CoreGraphics/CoreGraphics.h>
@implementation UIImage (Utils)
- (BOOL)isLightColor {
//获得主要颜色
UIColor *color = [self mostColor];
//获得主要颜色的RGB值
NSArray *components = [self RGBComponentsWithColor:color];
//RGB值分别相加,大于382的,定义为亮色
CGFloat num = [components[0] floatValue] + [components[1] floatValue] + [components[2] floatValue];
return num >382;
}
//来源网络:(链接遗失)
- (UIColor *)mostColor {
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
//第一步先把图片缩小加快计算速度.但越小结果误差可能越大
CGSize thumbSize=CGSizeMake(50,50);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
thumbSize.width,
thumbSize.height,
8,//bits per component
thumbSize.width*4,
colorSpace,
bitmapInfo);
CGRect drawRect = CGRectMake(0,0, thumbSize.width, thumbSize.height);
CGContextDrawImage(context, drawRect, self.CGImage);
CGColorSpaceRelease(colorSpace);
//第二步取每个点的像素值
unsignedchar* data = CGBitmapContextGetData (context);
if (data ==NULL)
{
CGContextRelease(context);
returnnil;
}
NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
for (int x=0; x<thumbSize.width; x++) {
for (int y=0; y<thumbSize.height; y++) {
int offset =4*(x*y);
int red = data[offset];
int green = data[offset+1];
int blue = data[offset+2];
int alpha = data[offset+3];
NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
[cls addObject:clr];
}
}
CGContextRelease(context);
//第三步找到出现次数最多的那个颜色
NSEnumerator *enumerator = [cls objectEnumerator];
NSArray *curColor = nil;
NSArray *MaxColor=nil;
NSUInteger MaxCount=0;
while ( (curColor = [enumerator nextObject]) !=nil )
{
NSUInteger tmpCount = [cls countForObject:curColor];
if ( tmpCount < MaxCount )continue;
MaxCount=tmpCount;
MaxColor=curColor;
}
return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f)
green:([MaxColor[1] intValue]/255.0f)
blue:([MaxColor[2] intValue]/255.0f)
alpha:([MaxColor[3] intValue]/255.0f)];
}
//获取RGB值
- (NSArray *)RGBComponentsWithColor:(UIColor *)color {
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
unsignedchar resultingPixel[4];
CGContextRef context = CGBitmapContextCreate(&resultingPixel,
1,
1,
8,
4,
rgbColorSpace,
bitmapInfo);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, CGRectMake(0,0,1,1));
CGContextRelease(context);
CGColorSpaceRelease(rgbColorSpace);
NSMutableArray *componets = [[NSMutableArray alloc]init];
for (int i =0; i <3; i++) {
[componets addObject:@(resultingPixel[i])];
}
return [componets mutableCopy];
}
- (UIImage *)scaleToSize:(CGSize)size {
//创建一个大小为size的image context,并将其设置为当前正在使用的context
UIGraphicsBeginImageContext(size);
//根据原图,绘制大小为size的图片
[self drawInRect:CGRectMake(0,0, size.width, size.height)];
//从当前的image context获得图片,此时图片为大小改变后的图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//当前image context出栈
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect frame = CGRectMake(0,0,1,1);
//创建一个image context,并将其设置为当前正在使用的context
UIGraphicsBeginImageContext(frame.size);
//获得当前正在使用的context
CGContextRef context = UIGraphicsGetCurrentContext();
//填充颜色
CGContextSetFillColorWithColor(context, [color CGColor]);
//设置填充区域
CGContextFillRect(context, frame);
//从当前的image context获得图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//当前image context出栈
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)trimWithRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
CGRect smallRect = CGRectMake(0,0, rect.size.width, rect.size.height);
//创建一个image context,并将其设置为当前正在使用的context
UIGraphicsBeginImageContext(smallRect.size);
//获得当前正在使用的context
CGContextRef context = UIGraphicsGetCurrentContext();
//绘制图片
CGContextDrawImage(context, smallRect, imageRef);
UIImage *image = [UIImage imageWithCGImage:imageRef];
//当前image context出栈
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)rotateImageWithImageName:(NSString *)imageName orientation:(UIImageOrientation)orientation {
CIImage *srcImage = [[CIImage alloc]initWithImage:[UIImage imageNamed:imageName]];
return [UIImage imageWithCIImage:srcImage scale:1.0 orientation:orientation];
}
//原始图片
+ (instancetype)imageWithOriginName:(NSString *)imageName
{
UIImage *img = [UIImage imageNamed:imageName];
return [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
+ (UIImage *)resizedImageWithName:(NSString *)name
{
return [self resizedImageWithName:name left:0.5 top:0.5];
}
+ (UIImage *)resizedImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top
{
UIImage *image = [self imageNamed:name];
return [image stretchableImageWithLeftCapWidth:image.size.width * left topCapHeight:image.size.height * top];
}
+(UIImage *)colorizeImage:(UIImage *)baseImage withColor:(UIColor *)theColor {
UIGraphicsBeginImageContext(baseImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0,0, baseImage.size.width, baseImage.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, area, baseImage.CGImage);
// CGContextDrawImage(ctx, area, baseImage.CGImage);
// CGContextDrawTiledImage(ctx, area, baseImage.CGImage);
[theColor set];
CGContextFillRect(ctx, area);
CGContextRestoreGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
// CGContextDrawImage(ctx, area, baseImage.CGImage); //改变背景
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
+(UIImage *)colorizeImage:(UIImage *)baseImage withBackgroundColor:(UIColor *)theColor {
UIGraphicsBeginImageContext(baseImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0,0, baseImage.size.width, baseImage.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSaveGState(ctx);
[theColor set];
CGContextFillRect(ctx, area);
CGContextRestoreGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextDrawImage(ctx, area, baseImage.CGImage); //改变背景
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
+(UIImage *)maskImage:(UIImage *)baseImage withImage:(UIImage *)theMaskImage {
UIGraphicsBeginImageContext(baseImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0,0, baseImage.size.width, baseImage.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGImageRef maskRef = theMaskImage.CGImage;
CGImageRef maskImage = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),NULL,false);
CGImageRef masked = CGImageCreateWithMask([baseImage CGImage], maskImage);
//CGImageRelease(maskImage);
//CGImageRelease(maskRef);
CGContextDrawImage(ctx, area, masked);
//CGImageRelease(masked);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
#import <UIKit/UIKit.h>
@interface UIColor (Utils)
/**
* 获取RGB颜色
*
*/
+(UIColor*)colorWithRed:(float)r Green:(float)g Blue:(float) b Alpha:(float) alpha;
/**
* 获取RGB颜色 alpha = 1
*
*/
+(UIColor*)colorWithRed:(float)r Green:(float)g Blue:(float) b;
/**
* 获取颜色的RGB值
*
*/
+(NSMutableArray*)getRGBComponentWithColor:(UIColor*)color;
/**
* 获取随机颜色
*
*/
+(UIColor*)colorWithRandomRGB;
/**
* 从十六进制字符串获取颜色,
* color:支持@“#123456”、 @“0X123456”、 @“123456”三种格式
*/
+ (UIColor *)colorWithHexString:(NSString *)color;
/**
* 根据颜色返回图片
*
*/
+(UIImage*) createImageWithColor: (UIColor*) color ;
/**
* 从十六进制字符串获取颜色,
*
*/
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;
/**
* 根据颜色获取 16进制字符串
*
*/
+(NSString *)stringFromColor:(UIColor *)color;
@end
#import "UIColor+Utils.h"
@implementation UIColor (Utils)
+(UIColor*)colorWithRed:(float)r Green:(float)g Blue:(float) b Alpha:(float) alpha
{
return [UIColor colorWithRed:(r) /255.0 green:(g) /255.0 blue:(b) /255.0 alpha:alpha] ;
}
+(UIColor*)colorWithRed:(float)r Green:(float)g Blue:(float) b
{
return [UIColor colorWithRed:r Green:g Blue:b Alpha:1];
}
/**
* 获取随机颜色
*
*/
+(NSMutableArray*)getRGBComponentWithColor:(UIColor*)color
{
NSMutableArray *RGBStrValueArr = [[NSMutableArray alloc] init];
NSString *RGBStr = nil;
//获得RGB值描述
NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
//将RGB值描述分隔成字符串
NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
//获取红色值
int r = [[RGBArr objectAtIndex:1] intValue] *255;
RGBStr = [NSString stringWithFormat:@"%d",r];
[RGBStrValueArr addObject:RGBStr];
//获取绿色值
int g = [[RGBArr objectAtIndex:2] intValue] *255;
RGBStr = [NSString stringWithFormat:@"%d",g];
[RGBStrValueArr addObject:RGBStr];
//获取蓝色值
int b = [[RGBArr objectAtIndex:3] intValue] *255;
RGBStr = [NSString stringWithFormat:@"%d",b];
[RGBStrValueArr addObject:RGBStr];
//返回保存RGB值的数组
return RGBStrValueArr;
}
+(UIColor*)colorWithRandomRGB
{
return [UIColor colorWithRed:arc4random_uniform(256) /255.0 green:arc4random_uniform(256) /255.0 blue:arc4random_uniform(256) /255.0 alpha:1] ;
}
/**
* 根据颜色返回图片
*
*/
+(UIImage*) createImageWithColor: (UIColor*) color
{
CGRect rect=CGRectMake(0,0,1,1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
//删除字符串中的空格
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] <6)
{
return [UIColor clearColor];
}
// strip 0X if it appears
//如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
if ([cString hasPrefix:@"0X"])
{
cString = [cString substringFromIndex:2];
}
//如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
if ([cString hasPrefix:@"#"])
{
cString = [cString substringFromIndex:1];
}
if ([cString length] !=6)
{
return [UIColor clearColor];
}
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsignedint r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float)r /255.0f) green:((float)g /255.0f) blue:((float)b /255.0f) alpha:alpha];
}
//默认alpha值为1
+ (UIColor *)colorWithHexString:(NSString *)color
{
return [self colorWithHexString:color alpha:1.0f];
}
/**
* 根据颜色获取 16进制字符串
*
*/
+(NSString *)stringFromColor:(UIColor *)color
{
const CGFloat *cs=CGColorGetComponents(color.CGColor);
NSString *r = [NSString stringWithFormat:@"%@",[self ToHex:cs[0]*255]];
NSString *g = [NSString stringWithFormat:@"%@",[self ToHex:cs[1]*255]];
NSString *b = [NSString stringWithFormat:@"%@",[self ToHex:cs[2]*255]];
return [NSString stringWithFormat:@"#%@%@%@",r,g,b];
}
+(NSString *)ToHex:(int)tmpid
{
NSString *endtmp=@"";
NSString *nLetterValue;
NSString *nStrat;
int ttmpig=tmpid%16;
int tmp=tmpid/16;
switch (ttmpig)
{
case10:
nLetterValue =@"A";break;
case11:
nLetterValue =@"B";break;
case12:
nLetterValue =@"C";break;
case13:
nLetterValue =@"D";break;
case14:
nLetterValue =@"E";break;
case15:
nLetterValue =@"F";break;
default:nLetterValue=[[NSString alloc]initWithFormat:@"%i",ttmpig];
}
switch (tmp)
{
case10:
nStrat =@"A";break;
case11:
nStrat =@"B";break;
case12:
nStrat =@"C";break;
case13:
nStrat =@"D";break;
case14:
nStrat =@"E";break;
case15:
nStrat =@"F";break;
default:nStrat=[[NSString alloc]initWithFormat:@"%i",tmp];
}
endtmp=[[NSString alloc]initWithFormat:@"%@%@",nStrat,nLetterValue];
return endtmp;
}
@end
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (Badge)
@property (strong,nonatomic) UILabel *badge;
// Badge value to be display
@property (nonatomic) NSString *badgeValue;
// Badge background color
@property (nonatomic) UIColor *badgeBGColor;
// Badge text color
@property (nonatomic) UIColor *badgeTextColor;
// Badge font
@property (nonatomic) UIFont *badgeFont;
// Padding value for the badge
@property (nonatomic) CGFloat badgePadding;
// Minimum size badge to small
@property (nonatomic) CGFloat badgeMinSize;
// Values for offseting the badge over the BarButtonItem you picked
@property (nonatomic) CGFloat badgeOriginX;
@property (nonatomic) CGFloat badgeOriginY;
// In case of numbers, remove the badge when reaching zero
@property BOOL shouldHideBadgeAtZero;
// Badge has a bounce animation when value changes
@property BOOL shouldAnimateBadge;
@end
#import <objc/runtime.h>
#import "UIBarButtonItem+Badge.h"
NSString const *badgeKey =@"badgeKey";
NSString const *badgeBGColorKey =@"badgeBGColorKey";
NSString const *badgeTextColorKey =@"badgeTextColorKey";
NSString const *badgeFontKey =@"badgeFontKey";
NSString const *badgePaddingKey =@"badgePaddingKey";
NSString const *badgeMinSizeKey =@"badgeMinSizeKey";
NSString const *badgeOriginXKey =@"badgeOriginXKey";
NSString const *badgeOriginYKey =@"badgeOriginYKey";
NSString const *shouldHideBadgeAtZeroKey =@"shouldHideBadgeAtZeroKey";
NSString const *shouldAnimateBadgeKey =@"shouldAnimateBadgeKey";
NSString const *badgeValueKey =@"badgeValueKey";
@implementation UIBarButtonItem (Badge)
@dynamic badgeValue, badgeBGColor, badgeTextColor, badgeFont;
@dynamic badgePadding, badgeMinSize, badgeOriginX, badgeOriginY;
@dynamic shouldHideBadgeAtZero, shouldAnimateBadge;
- (void)badgeInit
{
// Default design initialization
self.badgeBGColor = [UIColor redColor];
self.badgeTextColor = [UIColor whiteColor];
self.badgeFont = [UIFont systemFontOfSize:12.0];
self.badgePadding =6;
self.badgeMinSize =8;
self.badgeOriginX =self.customView.frame.size.width -self.badge.frame.size.width/2;
self.badgeOriginY = -4;
self.shouldHideBadgeAtZero =YES;
self.shouldAnimateBadge =YES;
// Avoids badge to be clipped when animating its scale
self.customView.clipsToBounds =NO;
}
#pragma mark - Utility methods
// Handle badge display when its properties have been changed (color, font, ...)
- (void)refreshBadge
{
// Change new attributes
self.badge.textColor =self.badgeTextColor;
self.badge.backgroundColor =self.badgeBGColor;
self.badge.font =self.badgeFont;
}
- (CGSize) badgeExpectedSize
{
// When the value changes the badge could need to get bigger
// Calculate expected size to fit new value
// Use an intermediate label to get expected size thanks to sizeToFit
// We don‘t call sizeToFit on the true label to avoid bad display
UILabel *frameLabel = [self duplicateLabel:self.badge];
[frameLabel sizeToFit];
CGSize expectedLabelSize = frameLabel.frame.size;
return expectedLabelSize;
}
- (void)updateBadgeFrame
{
CGSize expectedLabelSize = [self badgeExpectedSize];
// Make sure that for small value, the badge will be big enough
CGFloat minHeight = expectedLabelSize.height;
// Using a const we make sure the badge respect the minimum size
minHeight = (minHeight < self.badgeMinSize) ?self.badgeMinSize : expectedLabelSize.height;
CGFloat minWidth = expectedLabelSize.width;
CGFloat padding = self.badgePadding;
// Using const we make sure the badge doesn‘t get too smal
minWidth = (minWidth < minHeight) ? minHeight : expectedLabelSize.width;
self.badge.frame = CGRectMake(self.badgeOriginX,self.badgeOriginY, minWidth + padding, minHeight + padding);
self.badge.layer.cornerRadius = (minHeight + padding) /2;
self.badge.layer.masksToBounds =YES;
}
// Handle the badge changing value
- (void)updateBadgeValueAnimated:(BOOL)animated
{
// Bounce animation on badge if value changed and if animation authorized
if (animated &&self.shouldAnimateBadge && ![self.badge.text isEqualToString:self.badgeValue]) {
CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
[animation setFromValue:[NSNumber numberWithFloat:1.5]];
[animation setToValue:[NSNumber numberWithFloat:1]];
[animation setDuration:0.2];
[animation setTimingFunction:[CAMediaTimingFunction functionWithControlPoints:.4f :1.3f :1.f :1.f]];
[self.badge.layer addAnimation:animation forKey:@"bounceAnimation"];
}
// Set the new value
self.badge.text =self.badgeValue;
// Animate the size modification if needed
NSTimeInterval duration = animated ? 0.2 :0;
[UIView animateWithDuration:duration animations:^{
[self updateBadgeFrame];
}];
}
- (UILabel *)duplicateLabel:(UILabel *)labelToCopy
{
UILabel *duplicateLabel = [[UILabel alloc] initWithFrame:labelToCopy.frame];
duplicateLabel.text = labelToCopy.text;
duplicateLabel.font = labelToCopy.font;
return duplicateLabel;
}
- (void)removeBadge
{
// Animate badge removal
[UIView animateWithDuration:0.2 animations:^{
self.badge.transform = CGAffineTransformMakeScale(0,0);
} completion:^(BOOL finished) {
[self.badge removeFromSuperview];
self.badge =nil;
}];
}
#pragma mark - getters/setters
-(UILabel*) badge {
return objc_getAssociatedObject(self, &badgeKey);
}
-(void)setBadge:(UILabel *)badgeLabel
{
objc_setAssociatedObject(self, &badgeKey, badgeLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
// Badge value to be display
-(NSString *)badgeValue {
return objc_getAssociatedObject(self, &badgeValueKey);
}
-(void) setBadgeValue:(NSString *)badgeValue
{
objc_setAssociatedObject(self, &badgeValueKey, badgeValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// When changing the badge value check if we need to remove the badge
if (!badgeValue || [badgeValue isEqualToString:@""] || ([badgeValue isEqualToString:@"0"] && self.shouldHideBadgeAtZero)) {
[self removeBadge];
} elseif (!self.badge) {
// Create a new badge because not existing
self.badge = [[UILabel alloc] initWithFrame:CGRectMake(self.badgeOriginX,self.badgeOriginY,20,20)];
self.badge.textColor =self.badgeTextColor;
self.badge.backgroundColor =self.badgeBGColor;
self.badge.font =self.badgeFont;
self.badge.textAlignment = NSTextAlignmentCenter;
[self badgeInit];
[self.customView addSubview:self.badge];
[self updateBadgeValueAnimated:NO];
} else {
[self updateBadgeValueAnimated:YES];
}
}
// Badge background color
-(UIColor *)badgeBGColor {
return objc_getAssociatedObject(self, &badgeBGColorKey);
}
-(void)setBadgeBGColor:(UIColor *)badgeBGColor
{
objc_setAssociatedObject(self, &badgeBGColorKey, badgeBGColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self refreshBadge];
}
}
// Badge text color
-(UIColor *)badgeTextColor {
return objc_getAssociatedObject(self, &badgeTextColorKey);
}
-(void)setBadgeTextColor:(UIColor *)badgeTextColor
{
objc_setAssociatedObject(self, &badgeTextColorKey, badgeTextColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self refreshBadge];
}
}
// Badge font
-(UIFont *)badgeFont {
return objc_getAssociatedObject(self, &badgeFontKey);
}
-(void)setBadgeFont:(UIFont *)badgeFont
{
objc_setAssociatedObject(self, &badgeFontKey, badgeFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self refreshBadge];
}
}
// Padding value for the badge
-(CGFloat) badgePadding {
NSNumber *number = objc_getAssociatedObject(self, &badgePaddingKey);
return number.floatValue;
}
-(void) setBadgePadding:(CGFloat)badgePadding
{
NSNumber *number = [NSNumber numberWithDouble:badgePadding];
objc_setAssociatedObject(self, &badgePaddingKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self updateBadgeFrame];
}
}
// Minimum size badge to small
-(CGFloat) badgeMinSize {
NSNumber *number = objc_getAssociatedObject(self, &badgeMinSizeKey);
return number.floatValue;
}
-(void) setBadgeMinSize:(CGFloat)badgeMinSize
{
NSNumber *number = [NSNumber numberWithDouble:badgeMinSize];
objc_setAssociatedObject(self, &badgeMinSizeKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self updateBadgeFrame];
}
}
// Values for offseting the badge over the BarButtonItem you picked
-(CGFloat) badgeOriginX {
NSNumber *number = objc_getAssociatedObject(self, &badgeOriginXKey);
return number.floatValue;
}
-(void) setBadgeOriginX:(CGFloat)badgeOriginX
{
NSNumber *number = [NSNumber numberWithDouble:badgeOriginX];
objc_setAssociatedObject(self, &badgeOriginXKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self updateBadgeFrame];
}
}
-(CGFloat) badgeOriginY {
NSNumber *number = objc_getAssociatedObject(self, &badgeOriginYKey);
return number.floatValue;
}
-(void) setBadgeOriginY:(CGFloat)badgeOriginY
{
NSNumber *number = [NSNumber numberWithDouble:badgeOriginY];
objc_setAssociatedObject(self, &badgeOriginYKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self updateBadgeFrame];
}
}
// In case of numbers, remove the badge when reaching zero
-(BOOL) shouldHideBadgeAtZero {
NSNumber *number = objc_getAssociatedObject(self, &shouldHideBadgeAtZeroKey);
return number.boolValue;
}
- (void)setShouldHideBadgeAtZero:(BOOL)shouldHideBadgeAtZero
{
NSNumber *number = [NSNumber numberWithBool:shouldHideBadgeAtZero];
objc_setAssociatedObject(self, &shouldHideBadgeAtZeroKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
// Badge has a bounce animation when value changes
-(BOOL) shouldAnimateBadge {
NSNumber *number = objc_getAssociatedObject(self, &shouldAnimateBadgeKey);
return number.boolValue;
}
- (void)setShouldAnimateBadge:(BOOL)shouldAnimateBadge
{
NSNumber *number = [NSNumber numberWithBool:shouldAnimateBadge];
objc_setAssociatedObject(self, &shouldAnimateBadgeKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#import <Foundation/Foundation.h>
@interface NSDate (Utils)
/**
判断是否是今天
*/
-(BOOL)isToday;
/**
判断是否是昨天
*/
-(BOOL)isYesterday;
/**
判断是否是今年
*/
-(BOOL)isThisyear;
/**
获得2个时间的时间差
*/
-(NSDateComponents *)deltaFromNow;
/**
判断一个时间是否比另一个时间早
*/
-(BOOL)isEarlyThanDate:(NSDate *)otherDate;
/**
完成判断一个时间是否在8:23-11:46之间的功能
NSDate必须传8:23或23:45之类的格式
*/
- (BOOL)isBetweenFromTime:(NSDate *)fromDate toTime:(NSDate *)toDate;
@end
#import "NSDate+Utils.h"
@implementation NSDate (Utils)
-(BOOL)isToday
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitMonth;
NSDateComponents *selfDateComponents = [calendar components:unit fromDate:self];
NSDateComponents *nowDateComponents = [calendar components:unit fromDate:[NSDate date]];
return (selfDateComponents.year == nowDateComponents.year &&selfDateComponents.month == nowDateComponents.month && selfDateComponents.day == nowDateComponents.day);
}
-(BOOL)isYesterday
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *now = [NSDate date];
NSString *nowStr = [dateFormatter stringFromDate:now];
NSDate *nowDate=[dateFormatter dateFromString:nowStr];
NSString *selfStr = [dateFormatter stringFromDate:self];
NSDate *selfDate = [dateFormatter dateFromString:selfStr];
NSDateComponents *components = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];
return components.day ==1;
}
-(BOOL)isThisyear
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitYear;
NSDateComponents *selfDateComponents = [calendar components:unit fromDate:self];
NSDateComponents *nowDateComponents = [calendar components:unit fromDate:[NSDate date]];
return selfDateComponents.year == nowDateComponents.year;
}
-(NSDateComponents *)deltaFromNow
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
return [calendar components:unit fromDate:self toDate:[NSDate date] options:NSCalendarWrapComponents];
}
-(BOOL)isEarlyThanDate:(NSDate *)otherDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
NSDateComponents *d= [calendar components:unit fromDate:otherDate toDate:self options:NSCalendarWrapComponents];
long sec = [d hour]*3600+[d minute]*60+[d second];
if (sec >=900) {
returnNO;
}else
{
returnYES;
}
}
- (BOOL)isBetweenFromTime:(NSDate *)fromDate toTime:(NSDate *)toDate
{
NSDateFormatter *dateF1 = [[NSDateFormatter alloc]init];
dateF1.dateFormat = @"HH";
NSString *fromHour = [dateF1 stringFromDate:fromDate];
NSDateFormatter *dateF2 = [[NSDateFormatter alloc]init];
dateF2.dateFormat = @"mm";
NSString *fromMinute = [dateF2 stringFromDate:fromDate];
NSInteger minuteTotalFromBegin = [fromHour integerValue] * 60+[fromMinute integerValue];
NSDateFormatter *dateF = [[NSDateFormatter alloc]init];
dateF.dateFormat = @"HH:mm";
NSString *tempNow = [dateF stringFromDate:self];
NSDate *nowDate = [dateF dateFromString:tempNow];
NSString *fromHourNow = [dateF1 stringFromDate:nowDate];
NSString *fromMinuteNow = [dateF2 stringFromDate:nowDate];
NSInteger minuteTotalFromNow = [fromHourNow integerValue] * 60+[fromMinuteNow integerValue];
NSString *toHourEnd = [dateF1 stringFromDate:toDate];
NSString *toMinuteEnd = [dateF2 stringFromDate:toDate];
NSInteger minuteTotalFromEnd = [toHourEnd integerValue] * 60+[toMinuteEnd integerValue];
if (minuteTotalFromBegin < minuteTotalFromEnd) {
if (minuteTotalFromNow >=minuteTotalFromBegin && minuteTotalFromNow <=minuteTotalFromEnd) {
returnYES;
}else
{
returnNO;
}
}else
{
if ((minuteTotalFromNow >=minuteTotalFromBegin && minuteTotalFromNow <=24*60) ||(minuteTotalFromNow >=0 && minuteTotalFromNow <= minuteTotalFromEnd) ) {
returnYES;
}else
{
returnNO;
}
}
}
@end
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSString (Utils)
/**
* 计算字符串高度
*/
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize ;
/**
* 写入偏好设置
*/
-(void)saveToNSDefaultsWithKey:(NSString *)key;
/**
* 去除字符串中的空白字符
*/
-(NSString *)trimString ;
/**
* 获得UUID
* @return 返回uuid
*/
+ (NSString *)UUID;
/**
* 获取用户端的IP地址
*/
+ (NSString*)stringWithIP;
/**
* 检验字符串是否有效
* @return 若非空且不等于@“”,则返回YES,否则,返回NO
*/
- (BOOL)isEmptyString;
/**
* 判断是否有效邮箱
* @return 返回是否有效
*/
- (BOOL)isValidEmail;
/**
* 判断是否有效邮编
* @return 返回是否有效
*/
-(BOOL) isValidZipcode ;
/**
* 判断是否有效手机号码
* @return 返回是否有效
*/
- (BOOL)isValidPhone;
/**
* 判断是否有效身份证号码
* @return 返回是否有效
*/
- (BOOL)isValidIdCardNum;
/**
* 产生MD5
* @return MD5
*/
- (NSString *)MD5;
/**
* 根据文件路径计算文件大小
*/
- (NSInteger)fileSize ;
@end
#import "NSString+Utils.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (Utils)
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
NSDictionary *dict = @{NSFontAttributeName: font};
CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
return textSize;
}
-(void)saveToNSDefaultsWithKey:(NSString *)key
{
[[NSUserDefaults standardUserDefaults] setObject:self forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(NSString *)trimString
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
+ (NSString *)UUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
NSString* retStr = (__bridge_transfer NSString *)string;
return [[retStr stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
}
+ (NSString*)stringWithIP
{
NSString *address = @"an error occurred when obtaining ip address";
struct ifaddrs *interfaces =NULL;
struct ifaddrs *temp_addr =NULL;
int success =0;
success = getifaddrs(&interfaces);
if (success ==0) {// 0表示获取成功
temp_addr = interfaces;
while (temp_addr !=NULL) {
if( temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}
- (BOOL)isEmptyString {
return (self ==nil ||self.length ==0);
}
- (BOOL)isValidEmail {
BOOL sticterFilter =YES;
NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
NSString *laxString = @".+@.+\.[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = sticterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:self];
}
-(BOOL) isValidZipcode
{
constchar *cvalue = [self UTF8String];
int len = strlen(cvalue);
if (len !=6) {
returnFALSE;
}
for (int i =0; i < len; i++)
{
if (!(cvalue[i] >='0' && cvalue[i] <='9'))
{
returnFALSE;
}
}
returnTRUE;
}
- (BOOL)isValidPhone {
/**
* 手机号码
* 移动:134,135,136,137,138,139,150,151,152,157,158,159,182,183,187,188
* 联通:130,131,132,155,156,185,186
* 电信:133,153,180,189
*/
NSString * MOBILE = @"^((13[0-9])|(147)|(177)|(15[^4,\D])|(18[0,0-9]))\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
return [regextestmobile evaluateWithObject:self];
}
- (BOOL)isValidIdCardNum
{
NSString *value = [self copy];
value = [value stringByReplacingOccurrencesOfString:@"X" withString:@"x"];
value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
int length =0;
if (!value) {
returnNO;
}else {
length = (int)value.length;
if (length !=15 && length !=18) {
returnNO;
}
}
// 省份代码
NSArray *areasArray =@[@"11",@"12",@"13",@"14",@"15",@"21",@"22",@"23",@"31",@"32",@"33",@"34",@"35",@"36",@"37",@"41",@"42",@"43",@"44",@"45",@"46",@"50",@"51",@"52",@"53",@"54",@"61",@"62",@"63",@"64",@"65",@"71",@"81",@"82",@"91"];
NSString *valueStart2 = [value substringToIndex:2];
BOOL areaFlag =NO;
for (NSString *areaCodein areasArray) {
if ([areaCode isEqualToString:valueStart2]) {
areaFlag = YES;
break;
}
}
if (!areaFlag) {
returnNO;
}
NSRegularExpression *regularExpression;
NSUInteger numberofMatch;
int year =0;
switch (length) {
case15:
year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}else {
regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
numberofMatch = [regularExpression numberOfMatchesInString:value options:NSMatchingReportProgress range:NSMakeRange(0, value.length)];
if(numberofMatch >0) {
returnYES;
}else {
returnNO;
}
case18:
year = [value substringWithRange:NSMakeRange(6,4)].intValue;
if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19|20[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}else {
regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19|20[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
numberofMatch = [regularExpression numberOfMatchesInString:value options:NSMatchingReportProgress range:NSMakeRange(0, value.length)];
if(numberofMatch >0) {
int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
int Y = S %11;
NSString *M = @"F";
NSString *JYM = @"10X98765432";
M = [JYM substringWithRange:NSMakeRange(Y,1)];//判断校验位
if ([M isEqualToString:[[value substringWithRange:NSMakeRange(17,1)] uppercaseString]]) {
returnYES;//检测ID的校验位
}else {
returnNO;
}
}else {
returnNO;
}
default:
returnNO;
}
returnNO;
}
- (NSString *)MD5 {
constchar *cStr = [self UTF8String];
unsignedchar digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH *2];
for (int i =0; i < CC_MD5_DIGEST_LENGTH; i++) {
[result appendFormat:@"%02x",digest[i]];
}
return result;
}
- (NSString*)md532BitLower
{
constchar *cStr = [self UTF8String];
unsignedchar result[16];
NSNumber *num = [NSNumber numberWithUnsignedLong:strlen(cStr)];
CC_MD5( cStr,[num intValue], result );
return [[NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] lowercaseString];
}
- (NSString*)md532BitUpper
{
constchar *cStr = [self UTF8String];
unsignedchar result[16];
NSNumber *num = [NSNumber numberWithUnsignedLong:strlen(cStr)];
CC_MD5( cStr,[num intValue], result );
return [[NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] uppercaseString];
}
- (NSInteger)fileSize {
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL isDirectory =NO;
BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory];
if(!exists)return0;
if(isDirectory) {
NSInteger size = 0;
NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
for(NSString *subpathin enumerator) {
NSString *fullSubPath = [self stringByAppendingPathComponent:subpath];
size += [mgr attributesOfItemAtPath:fullSubPath error:nil].fileSize;
}
return size;
}else{
return [mgr attributesOfItemAtPath:self error:nil].fileSize;
}
}
@end
最后
以上就是文艺高跟鞋为你收集整理的iOS常用UI分类的全部内容,希望文章能够帮你解决iOS常用UI分类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复