获取当前控制器(UIView)
- (UIViewController *)currentViewController {
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal){
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows){
if (tmpWin.windowLevel == UIWindowLevelNormal){
window = tmpWin;
break;
}
}
}
UIViewController *result = window.rootViewController;
while (result.presentedViewController) {
result = result.presentedViewController;
}
if ([result isKindOfClass:[UITabBarController class]]) {
result = [(UITabBarController *)result selectedViewController];
}
if ([result isKindOfClass:[UINavigationController class]]) {
result = [(UINavigationController *)result topViewController];
}
return result;
}
获取当前控制器(NSObj)
#pragma 获取当前控制器
- (UIViewController *)currentViewController {
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
return [self findBestViewController:viewController];
}
- (UIViewController*)findBestViewController:(UIViewController*)vc {
if (vc.presentedViewController) {
return [self findBestViewController:vc.presentedViewController];
} else if ([vc isKindOfClass:[UISplitViewController class]]) {
UISplitViewController* svc = (UISplitViewController*)vc;
if (svc.viewControllers.count > 0) {
return [self findBestViewController:svc.viewControllers.lastObject];
} else {
return vc;
}
} else if ([vc isKindOfClass:[UINavigationController class]]) {
UINavigationController* nvc = (UINavigationController*)vc;
if (nvc.viewControllers.count > 0) {
return [self findBestViewController:nvc.topViewController];
} else {
return vc;
}
} else if ([vc isKindOfClass:[UITabBarController class]]) {
UITabBarController* tvc = (UITabBarController*)vc;
if (tvc.viewControllers.count) {
return [self findBestViewController:tvc.selectedViewController];
} else {
return vc;
}
} else {
return vc;
}
}
画一个虚线图(UIImage分类方法)
-
使用方法:
self.textView.layer.contents = (id)[UIImage imageWithSize:self.textView.bounds.size borderColor:RGBA(0xB8C1CE, 0.7) borderWidth:1.0f].CGImage;
-
代码:
+ (UIImage*)imageWithSize:(CGSize)size borderColor:(UIColor *)color borderWidth:(CGFloat)borderWidth {
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[[UIColor clearColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, borderWidth);
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGFloat lengths[] = { 3, 1 };
CGContextSetLineDash(context, 0, lengths, 1);
CGContextMoveToPoint(context, 0.0, 0.0);
CGContextAddLineToPoint(context, size.width, 0.0);
CGContextAddLineToPoint(context, size.width, size.height);
CGContextAddLineToPoint(context, 0, size.height);
CGContextAddLineToPoint(context, 0.0, 0.0);
CGContextStrokePath(context);
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
圆角图(UIImage分类方法)
-
使用方法:
UIImage *placeHolder = [UIImage imageNamed:@"defaultUserIcon"].roundImage;
-
代码:
- (UIImage *)roundImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
CGContextAddEllipseInRect(ctx, rect);
CGContextClip(ctx);
[self drawRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
1.获取富文本字典(2和3都基于这个富文本)
- (NSDictionary *)getAttributesDict {
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
paraStyle.alignment = NSTextAlignmentLeft;
paraStyle.lineSpacing = 1.0f; //设置行间距
paraStyle.hyphenationFactor = 0.5;
paraStyle.firstLineHeadIndent = 0.0;
paraStyle.paragraphSpacingBefore = 0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
//设置字间距 NSKernAttributeName:@0.5f
NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0f], NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@0.5f };
return dict;
}
2.传入一个lable,并设置行间距和字间距
- (void)setLabelFont:(UILabel *)label {
NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:label.text attributes:[self getAttributesDict]];
label.attributedText = attributeStr;
}
3.计算由“2”设置的Label高度
- (CGFloat)getSpaceLabelHeight: (NSString *)string LabelWidth: (CGFloat)labelWidth {
CGSize size = [string boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:[self getAttributesDict] context:nil].size;
return size.height;
}
获取单行label宽度
- (CGFloat)sigleLineLabelWidth:(UILabel *)label {
CGSize size =[self.timeLabel.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
return size.width;
}
获取 UITextView 的光标位置
CGFloat cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin.y;
超出父控件接受点击
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
return nil;
}
/**
* 此注释掉的方法用来判断点击是否在父View Bounds内,
* 如果不在父view内,就会直接不会去其子View中寻找HitTestView,return 返回
*/
// if ([self pointInside:point withEvent:event]) {
for (UIView *subview in self.subviews) {
CGPoint convertedPoint = [subview convertPoint:point fromView:self];
UIView *hitTestView = [subview hitTest:convertedPoint withEvent:event];
if (hitTestView) {
return hitTestView;
}
}
return [super hitTest:point withEvent:event];
// }
return nil;
}
扩大点击热区
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
return CGRectContainsPoint(HitTestingBounds(self.bounds, 200, 300), point);
}
CGRect HitTestingBounds(CGRect bounds, CGFloat minimumHitTestWidth, CGFloat minimumHitTestHeight) {
CGRect hitTestingBounds = bounds;
if (minimumHitTestWidth > bounds.size.width) {
hitTestingBounds.size.width = minimumHitTestWidth;
hitTestingBounds.origin.x -= (hitTestingBounds.size.width - bounds.size.width)/2;
}
if (minimumHitTestHeight > bounds.size.height) {
hitTestingBounds.size.height = minimumHitTestHeight;
hitTestingBounds.origin.y -= (hitTestingBounds.size.height - bounds.size.height)/2;
}
return hitTestingBounds;
}
转移点击处理
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *hitTestView = [super hitTest:point withEvent:event];
if (hitTestView) {
hitTestView = self.scrollView;
}
return hitTestView;
}
Enumerator使用
- (void)objectEnumeratorWithArray: (NSArray *)array {
NSLog(@"------- 枚举器法---------");
//ObjectEnumerator 正序
//reverseObjectEnumerator 逆序
NSEnumerator *enumerator = [array reverseObjectEnumerator];
id obj = nil;
while (obj = [enumerator nextObject]) {
NSLog(@"%@", obj);
}
//2.倒序的数组
NSArray* reversedArray = [[array reverseObjectEnumerator] allObjects];
}
生成条形码
- (UIImage *)generateBarCode:(NSString *)code width:(CGFloat)width height:(CGFloat)height {
//生成条形码图片
CIImage *barcodeImage;
NSData *data = [code dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
barcodeImage = [filter outputImage];
//消除模糊
CGFloat scaleX = width / barcodeImage.extent.size.width;
CGFloat scaleY = height / barcodeImage.extent.size.height;
CIImage *transformedImage = [barcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
return [UIImage imageWithCIImage:transformedImage];
}
RAC使用
- (void)rac_map_function {
RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id subscriber) {
[subscriber sendNext:@"A signal"];
[subscriber sendCompleted];
return [RACDisposable disposableWithBlock:^{
}];
}];
signal = [signal map:^id(id value) {
return @"B signal";
}];
[signal subscribeNext:^(id x) {
NSLog(@"%@", x);
}];
}
透明图
- (UIImage *)image {
//self.navigationController.navigationBar.translucent = YES;
UIGraphicsBeginImageContext(self.navigationController.navigationBar.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4].CGColor);
CGContextFillRect(context, self.navigationController.navigationBar.frame);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
return image;
}
App版本号
//Version
[[[NSBundle mainBundle]infoDictionary]valueForKey:@"CFBundleShortVersionString"];
//Build
[[[NSBundle mainBundle]infoDictionary]valueForKey:@"CFBundleVersion"];
调整UIButton上下显示
CGFloat margin = 12.0f;
CGSize imageSize = button.imageView.frame.size;
CGSize titleSize = button.titleLabel.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, -imageSize.height-margin, 0);
button.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height-margin, 0, 0, -titleSize.width);
二维码的生成
- (UIImage *)createQRCode:(NSString *)code length: (CGFloat)length {
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setDefaults];
NSData *infoData = [code dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:infoData forKeyPath:@"inputMessage"];
CIImage *outImage = [filter outputImage];
return [self createNonInterpolatedUIImageFormCIImage:outImage length:length];
}
//根据CIImage生成指定大小的UIImage
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image length:(CGFloat) length {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(length/CGRectGetWidth(extent), length/CGRectGetHeight(extent));
// 1.创建bitmap;
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
配置隐私权限 保存到相册=============
Privacy - Photo Library Additions Usage Description
UIImageWriteToSavedPhotosAlbum(shareImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
并实现代理
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSString *msg = nil ;
if(error){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
}
====================
//生成图片(屏幕截图)
- (UIImage *)creatShareImage {
UIGraphicsBeginImageContextWithOptions(self.imgView.frame.size, NO, 2.0);
[self.imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *shareImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return shareImg;
}
环境配置
#ifdef DEBUG
//开发环境
#define kUrlApi @"https://develop.com"
#else
//正式环境
#define kUrlApi @"https://release.com"
#endif