小技巧

2017-10-03  本文已影响10人  Vijay_

获取主bundle下的info.plist的字典对象 [NSBundle mainBundle].infoDictionary

场景:使用KVC赋值
有时候某个对象的属性是结构体 但是KVC只能把一个对象赋值给某个对象的Key
这时候就需要用到NSValue将结构体转换成NSValue对象进行赋值


transform3d keyPath guide
[_image.layer setValue:[NSValue valueWithCATransform3D
:CATransform3DMakeRotation(M_PI, 1, 1, 0)] forKey:@"transform"];
//在CATransform3D中用到KVC的场景是可以快速赋值形变
//可以根据官方文档直接用keyPath给transform的某个结构进行形变
//在x轴为1的地方进行旋转
[_image setValue:@1 forKeyPath:@"layer.transform.rotation.x"];
//在x轴y轴为1的向量方向旋转
[_image setValue:@1 forKeyPath:@"layer.transform.rotation"];

场景:进入页面的广告图显示导航栏为黑色 进到应用里时导航栏为白色 显示一个过渡效果, 操作如下:

//修改状态栏风格 默认的是黑色 UIStatusBarStyleLightContent是白色
[[UIAppliction sharedAppliction] setStatusBar:xxx]
//注 需要在info.list添加(关闭项目设置的状态栏风格)
View controller-based status bar appearance   :NO

场景:TabBarController中的某个viewcontrol是navigationController并且该控制器中转跳时需要隐藏TabBar。

//给转跳的视图控制器设置hidesBottomBarWhenPushed即可
    Upload* up = [[Upload alloc] init];
    up.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:up animated:YES];

场景:图片自适应比例

//设置imageView的contentMode来调整图片显示方式
UIImageView* iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"latest.png"]];
    iv.frame = CGRectMake(20, 50, 26, 26);
    iv.contentMode = UIViewContentModeTopLeft;

场景:统一设置TabBarItem的字体常用修改字体属性

[[UITabBarItem appearance] setTitleTextAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:RGB(255, 255, 255), NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
//选中状态 (此处RGB是我定义的宏函数)
    [[UITabBarItem appearance] setTitleTextAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:RGB(255, 204, 153), NSForegroundColorAttributeName,nil] forState:UIControlStateSelected];

场景:创建圆角按钮或者图形

//设置圆角半径
view.layer.cornerRadius = $num;
view.layer.masksToRounds = YES;

设置cell阴影需要设置在tableview上

//需要先导入框架
#import "QuartzCore/QuartzCore.h"
//偏移量
 _tableView.layer.shadowOffset = CGSizeMake(0, 2);
//延伸
    _tableView.layer.shadowRadius = 1;
    _tableView.layer.shadowOpacity = 0.5;
    _tableView.layer.shadowColor = [UIColor blackColor].CGColor;

场景:隐藏键盘的联想功能

[_field setAutocorrectionType:UITextAutocorrectionTypeNo];
    [_field setAutocapitalizationType:UITextAutocapitalizationTypeNone];

场景:设置键盘左边距(右边距则是right)以及限制输入长度

//设置左内边距
 _field.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 0)];
    _field.leftViewMode = UITextFieldViewModeAlways;
//设置限制输入长度
    [_field addTarget:self action:@selector(adjustMax:) forControlEvents:UIControlEventEditingChanged];
- (void)adjustMax:(UITextField*)field{
    if (field.text.length > 10) {
        field.text = [field.text substringToIndex:10];
    }
}

场景:隐藏navigationBar的底部分割线

//其实是找到背景view隐藏掉那个背景view
 [[self.navigationController.navigationBar.subviews firstObject] setHidden:YES];

场景:给view添加上下左右边框

//创建一个layer 给layer加上样式后添加到视图的layer上
 CALayer* bottomlayer = [CALayer layer];
        CGFloat y = h - 1.f;
        
        bottomlayer.frame = CGRectMake(0, y, w, 1.f);
        bottomlayer.backgroundColor = RGB(255, 0, 0).CGColor;
        [label.layer addSublayer:bottomlayer];

场景:设置presentViewController的视图控制器背景透明

ViewController* vc = [[ViewController alloc] init];
//关键语句
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:vc animated:YES completion:^{
        NSLog(@"--");
    }];

场景:app默认不允许旋转屏幕,在特定页面允许旋转

//AppDelegate.h
@property BOOL allowRotation;
//AppDelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
//如果设置允许旋转则设置app允许旋转
  if(self.allowRotation){
return UIInterfaceOrientationMaskAll;
}
    return UIInterfaceOrientationMaskPortrait;
}
//viewDidLoad
AppDelegate* app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    app.allowRotation = YES;
//viewDidDisappear
AppDelegate* app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    app.allowRotation = NO;

场景:代码调用旋转屏幕

- (void)orientationToPortrait:(UIInterfaceOrientation)orientation {
    SEL selector = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val = orientation;
    [invocation setArgument:&val atIndex:2];//前两个参数已被target和selector占用
    [invocation invoke];
    
}

场景:设置uiview动画过渡效果

 [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    //    设置过渡动画 (翻页)
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
[UIView commitAnimations];

场景:解析plist等文件

NSURL* url = [[NSBundle mainBundle] URLForResource:@"aalist" withExtension:@"plist"];
    NSDictionary* dic = [NSDictionary dictionaryWithContentsOfURL:url];
    NSLog(@"%@",dic);
    NSString* str = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str);

UIApplication方法

 // uiapplication
    // 1. 设置图标标记
    // 2. 显示联网转圈
    // 3. 设置状态栏样式
    // 4. 打开网页
    UIApplication *app = [UIApplication sharedApplication];
    
    [app registerUserNotificationSettings:
     [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil]];
    app.applicationIconBadgeNumber = 10;
    
    app.networkActivityIndicatorVisible = YES;


    [app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    
    [app openURL:[NSURL URLWithString:@"http://www.baidu.com"] options:@{} completionHandler:nil];


场景:判断某个对象是否能响应某个方法(判断是否有某个属性)

 BOOL b = [Flag instancesRespondToSelector:@selector(setIcon:)];
    NSLog(@"%i",b);

场景:拦截文本框输入文字(代码赋值不算,只拦截用户输入)

//绑定代理UITextFieldDelegate
textfield.delegate = xxx;
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//返回NO就是输入无效  可以用户输入的内容是否在有效返回内 如果是就返回YES 不是就返回NO
    return NO;
}

场景:关闭uitableviewcontrol的系统自动设置额外滚动区


- (void)viewDidLoad {
   [super viewDidLoad];
   UIView *header = [[UIView alloc] >initWithFrame:CGRectMake(0, 0, 0, 300)];
   header.backgroundColor = [UIColor greenColor];
   self.tableView.tableHeaderView = header;
   self.automaticallyAdjustsScrollViewInsets = NO;
}
结果

场景:storyboard或者xib设置约束时出现有边距

点击 image.png
去掉constrain to margins即可

场景:存储数据到plist文件中

NSString* cachesPath =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString* path = [cachesPath stringByAppendingPathComponent:@"arr.plist"];
    NSArray* arr = @[@1,@2];
    [arr writeToFile:path atomically:YES];
//读取
[NSArray arrayWithContentsOfFile:path];

*场景:不知道是哪个文本框的键盘(关闭当前视图所弹出的键盘)

[self.view endEditing:YES];
//设置控制器页面退出时关闭键盘 必须在willDisappear中在DidAppear中控制器获取不到键盘响应
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

场景*获取当前App的主window

UIWindow *window = [UIApplication shareApplication].keyWindow;

场景拖拽控件

@interface ViewController ()<UIGestureRecognizerDelegate>{
    CGPoint ori;
}
@property (weak, nonatomic) IBOutlet UIView *moveView;
@end

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
//由于上一个点变量会保存手势移动的最后一个数值 
//导致下次移动时开始数值与上次移动的结束数值相减发生错误  
//所以需要在每次手势开始时初始化上个坐标点
    ori = CGPointZero;
    return YES;
}
- (IBAction)moving:(UIPanGestureRecognizer *)sender {
    CGPoint p = [sender translationInView:self.view];
    _moveView.transform = CGAffineTransformTranslate(_moveView.transform,  p.x - ori.x, p.y - ori.y);
    ori = p;
}

场景:图片显示

 UIImageView *uv = [[UIImageView alloc] initWithFrame:rect];
    uv.image = [UIImage imageNamed:@"timg"];
//scaleAspectFit是高或者宽(较长的一边)适应frame,并保持比例不变
//scaleAspectFill是高或宽(较短的一边)适应frame,并保持不变,图片会超出frame需要隐藏
    uv.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:uv];

场景:获取静态图片原始高宽

//UIImage会带有一个size 当读取图片后就可以获取该图片的原始高宽
UIImage.size

场景:判断某个点是否在某个rect范围内

CGRectContainsPoint(<#CGRect rect#>, <#CGPoint point#>);

场景:获取时间操作

// 获取指定格式的当前时间字符串
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY:MM:dd"];
        NSString *str = [formatter stringFromDate:[NSDate date]];
        // 根据当前时间获取到当前calendar日期类 
        NSCalendar *calendar = [NSCalendar currentCalendar];
        // 然后根据单位获取到年月日等单独信息
        NSInteger year = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
        NSLog(@"%li",year);

        // 也可以一次获取多个单位日期
          NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *cmp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
        
        NSLog(@"%li",cmp.year);
        NSLog(@"%li",cmp.month);
        NSLog(@"%li",cmp.day);

UIImageView播放动画(gif)

$imageView.animationImages = @[UIImage1,UIImage2,...];
$imageView.animationDuration = 0.5;
[$imageView startAnimating];

拉伸图片
stretchableImageWithLeftCapWidth:<#(NSInteger)#> topCapHeight:<#(NSInteger)#>

字符串转字典

NSString * str = @"{\"name\":\"vijay\"}";
NSDictionary dic =[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding options:kNilOptions error:nil];

通过类名字符串创建类

//获取到字符串对应的类 
//但是最好不要用字符串 最好是用Class属性作为属性 参数等 
Class desClass = NSClassFromString( @"hello");
    UIViewController *vc = [[desClass alloc] init];

弹出键盘视图

//必须要把文本框添加到视图上becomeFirstResponder才有效
UITextField *textField = [[UITextField alloc] init];
[textField becomeFirstResponder];
[self.view addSubView:textField];
//关闭可以是 
[textField resignFirstResponder ];
//也可以用当前的父类关闭所有键盘
[self.view endEditing:YES ]

自定义类泛型 并应用到属性

#import <Foundation/Foundation.h>
//相当于声明该类时顺便传一个属性进来并应用到所有以该属性声明的 本类属性或者方法上
@interface Person<ObjectType> : NSObject

@property (nonatomic,strong) NSMutableArray<ObjectType> *arr;
@property (nonatomic,strong) ObjectType age;
@end

上一篇下一篇

猜你喜欢

热点阅读