一、设置导航栏透明
@property (nonatomic,assign) BOOL isAnimated;
///导航栏透明
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:_isAnimated];
[self setUI];
[self requestData];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
if (self.navigationController.viewControllers.count > 1) {
_isAnimated = YES;
[self.navigationController setNavigationBarHidden:NO animated:YES];
}else{
_isAnimated = NO;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
_isAnimated = NO;
}
二、复制到剪切板
UIPasteboard *appPasteBoard = [UIPasteboard generalPasteboard];
[appPasteBoard setString:“要复制的文字”];
三、获取AppDelegate
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
四、单例的多线程写法
------DataManager.h
+ (instancetype)shareManager
@property (nonatomic, strong) NSString *NAME;
------DataManager.m
#import "DataManager.h"
@interface DataManager()<NSCopying,NSMutableCopying>
@end
static DataManager *manager = nil;
@implementation DataManager
+ (instancetype)shareManager{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[self alloc]init];
});
return manager;
}
+ (id)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [super allocWithZone:zone];
});
return manager;
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
return manager;
}
- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {
return manager;
}
@end
--------main
导入头文件后
ShareManage *manage = [ShareManage shareManager];
manage.NAME = @"测试单例,输出名称";
NSLog(@"------%@-------",manage.NAME)
--------其他页面
ShareManage *manage = [ShareManage shareManager];
NSLog(@"------%@-------",manage.NAME)
可获取NAME属性值
五、倒计时
/// 定时器
@property(nonatomic,strong)dispatch_source_t timer;
///倒计时
-(void)countDownAction{
if (self.timer) {
dispatch_cancel(self.timer);
self.timer = nil;
}
self.postBut.userInteractionEnabled = NO;
__block NSInteger count = 60;
dispatch_queue_t queue = dispatch_get_main_queue();
//创建一个定时器(dispatch_source_t本质上还是一个OC对象)
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//设置定时器的各种属性
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0*NSEC_PER_SEC));
uint64_t interval = (uint64_t)(1.0*NSEC_PER_SEC);
dispatch_source_set_timer(self.timer, start, interval, 0);
//设置回调
__weak typeof(self) weakSelf = self;
dispatch_source_set_event_handler(self.timer, ^{
count--;
if (count==0) {
dispatch_source_cancel(weakSelf.timer);
weakSelf.timer = nil;
[self.postBut setTitle:@"发送验证码" forState:UIControlStateNormal];
self.postBut.userInteractionEnabled = YES;
}else{
[self.postBut setTitle:[NSString stringWithFormat:@"重发(%ld)",(long)count] forState:UIControlStateNormal];
}
});
//启动定时器(默认是暂停)
dispatch_resume(self.timer);
}
六、富文本 字符串拼接
///拼接-工分:
///range富文本
NSString *deposit = [NSString stringWithFormat:@"%@",self.roomDic[@"deposit"]];
_earnestLabel.text = [NSString stringWithFormat:@"定金: %@ 工分",deposit];
NSRange tempRange = [_earnestLabel.text rangeOfString:deposit];
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc]initWithString:_earnestLabel.text];
[attributeStr addAttribute:NSForegroundColorAttributeName value:RGB_COLOR(255, 91, 0) range:tempRange]; [attributeStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:tempRange];
_earnestLabel.attributedText = attributeStr;
七、获取当前时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString * str = [formatter stringFromDate:[NSDate date]];
八、获取指定view的截图并保存到相册
//传入需要截取的view
-(UIImage *)screenShotView:(UIView *)view{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.frame.size.width,view.frame.size.height ), NO, 0.0); //currentView 当前的view 创建一个基于位图的图形上下文并指定大小为
[view.layer renderInContext:UIGraphicsGetCurrentContext()];//renderInContext呈现接受者及其子范围到指定的上下文
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();//返回一个基于当前图形上下文的图片
UIGraphicsEndImageContext();//移除栈顶的基于当前位图的图形上下文
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);//然后将该图片保存到图片图
return viewImage;
}
九、计算文字宽度
NSDictionary *attrs = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:9]};
CGSize size = [cell.shopType.text sizeWithAttributes:attrs];
十、快速获取数组的总和,平均值,最大,最小值
- (void)caculateArray:(NSArray *)array{
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min);
// return [NSString stringWithFormat:@"%f",sum];
}
十一、弹出拨打电话
1.NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",phoneBumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:^(BOOL success) {
}];
2.NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phoneBumber];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
十二、判断手势方向
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];
if (translation.y>0) {
// NSLog(@"----------下-----------");
}else if(translation.y<0){
// NSLog(@"----------上-----------");
}
///例:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGPoint translation = [self.bgScrollView.panGestureRecognizer translationInView:_bgScrollView.superview];
if (translation.y>0) {
NSLog(@"----------下-----------");
}else if(translation.y<0){
NSLog(@"----------上-----------");
}
}
十三、字符串生成二维码保存到相册
-(void)generatingTwoDimensionalCode {
// 创建过滤器
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 过滤器恢复默认
[filter setDefaults];
// 给过滤器添加数据
NSString *string = [NSString stringWithFormat:@"%@",NET_IMAGE(self.dataDic[@"data"][@"code"])];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[filter setValue:data forKeyPath:@"inputMessage"];
// 获取二维码过滤器生成的二维码
CIImage *image = [filter outputImage];// 此时的 image 是模糊的
// 高清处理:将获取到的二维码添加到
UIImage *imagex = [self createNonInterpolatedUIImageFormCIImage:image withSize:300];// withSize 大于等于视图显示的尺寸
UIImageWriteToSavedPhotosAlbum(imagex, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
//--生成高清二维码
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 创建 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);
// 保存 bitmap 到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}
- (void)loadImageFinished:(UIImage *)image{
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
十四、数组拼接、字符串分割
///数组以某个元素拼接
[dic setObject:[imageArr componentsJoinedByString:@","] forKey:@"img"];
///字符串以某元素分割
NSArray *imgArr = [NSArray array];
imgArr = [self.postDataArr[indexPath.row][@"img"] componentsSeparatedByString:@","];
十五、随机颜色
- (UIColor *)randomColor{
return [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
}
十六、通知
实现方法.m
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(action) name:@"JUMPTOHOME" object:nil];
-(void)action {
///通知执行的方法
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"JUMPTOHOME" object:nil];
}
调用.m
[[NSNotificationCenter defaultCenter]postNotificationName:@"JUMPTOHOME" object:nil];
十七、修改字符串中的字符(修改相同的每个字符为另一字符)
NSString *phoneStr = [self.phoneTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
十八、延时器
//第一种:
[self performSelector:@selector(nextQuestion:) withObject:nil afterDelay:2.0];
//第二种:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//需要调用的方法
});
//第三种:
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1/*延迟执行时间*/ * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
[self.textField becomeFirstResponder];
});
十九、引入WKwebView 手机适配 防止超出屏幕边界
-(WKWebView *)webView {
if (!_webView) {
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
// _webView.userInteractionEnabled = NO;
_webView.navigationDelegate = self;
_webView.scrollView.bounces = NO;
_webView.scrollView.alwaysBounceVertical = NO;
// _webView.scrollView.scrollEnabled = NO;
_webView.UIDelegate = self;
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}
return _webView;
}
二十、应用间的跳转
NSURL *URL = [NSURL URLWithString:@"appB://ios.myapp.cn"];
[[UIApplication sharedApplication] openURL:URL];
二十一、手势识别
UITapGestureRecognizer(点按)
UILongPressGestureRecognizer(长按)
UISwipeGestureRecognizer(轻扫)
UIRotationGestureRecognizer(旋转)
UIPanGestureRecognizer(拖动)
UIPinchGestureRecognizer(捏合,用于缩放)
- 例:长按手势
//1.创建一个手势 并且监听
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
//最小触发 按压的时间
longPress.minimumPressDuration = 2.0;
//允许多大范围内 触发
longPress.allowableMovement = 20;
//2.添加到当前你想 操作的控件上
[self.myImageVIew addGestureRecognizer:longPress];
二十二、点击tableviewCell,collectionView 滚动到固定的session
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes*attributes = [self.collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row]];
CGRect rect = attributes.frame;
[self.collectionView setContentOffset:CGPointMake(self.collectionView.frame.origin.x, rect.origin.y - 28) animated:YES];
}
注:28: session 头高度
二十三、collectionView 获取当前点击的item
SelectMultipleCategoriesCollectionViewCell * cell = (SelectMultipleCategoriesCollectionViewCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];
二十四、NSUserDefaults存取
[[NSUserDefaults standardUserDefaults] setObject:@"exampleObject" forKey:@"exampleKey"];//存
[[NSUserDefaults standardUserDefaults] objectForKey:@"exampleKey"];//取
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"exampleKey"];//移除
///写入
//1. 获取系统的偏好设置对象
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//2. 存储数据
[defaults setObject:@"小明" forKey:@"name"];
[defaults setInteger:100 forKey:@"age"];
[defaults setBool:NO forKey:@"isTrue"];
//3.立即同步: 强制写入
[defaults synchronize];
///读取
//1.获取到偏好设置的路径
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//2.读取数据
NSString *name = [defaults objectForKey:@"name"];
NSInteger age = [defaults integerForKey:@"age"];
BOOL isTrue = [defaults boolForKey:@"isTrue"];
二十五、tableview 滚动到指定行
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.commendDataArr.count -1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
二十六、TextField 限制只可输入数字
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
return NO;
}
return YES;
}
二十七、WriteToFile
///写入数据
//1.1 你需要获取路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// .XXX 尾椎 只是决定 以哪中方式查看数据, 对存入的数据本身没有影响
NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"];
//1.2 写数据
NSArray *dataArray = @[@"亚洲国际舞王尼古拉斯赵四",@"小明",@"老王",@"霜霜"]; //1.3 存 //atomically 原子性的,数据安全的, 百分之九十九都是YES
[dataArray writeToFile:fiflePath atomically:YES];
///读取数据
//1.读取路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"];
//2.取出来
NSArray *dataArray = [NSArray arrayWithContentsOfFile:fiflePath];
二十八、价格键盘只可输入数字和点
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL isHaveDian;
//判断是否有小数点
if ([textField.text containsString:@"."]) {
isHaveDian = YES;
}else{
isHaveDian = NO;
}
if (string.length > 0) {
//当前输入的字符
unichar single = [string characterAtIndex:0];
NSLog(@"single = %c",single);
//不能输入.0~9以外的字符
if (!((single >= '0' && single <= '9') || single == '.')){
NSLog(@"您输入的格式不正确");
return NO;
}
//只能有一个小数点
if (isHaveDian && single == '.') {
NSLog(@"只能输入一个小数点");
return NO;
}
//如果第一位是.则前面加上0
if ((textField.text.length == 0) && (single == '.')) {
textField.text = @"0";
}
//如果第一位是0则后面必须输入.
if ([textField.text hasPrefix:@"0"]) {
if (textField.text.length > 1) {
NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
if (![secondStr isEqualToString:@"."]) {
NSLog(@"第二个字符必须是小数点");
return NO;
}
}else{
if (![string isEqualToString:@"."]) {
NSLog(@"第二个字符必须是小数点");
return NO;
}
}
}
//小数点后最多能输入两位
if (isHaveDian) {
NSRange ran = [textField.text rangeOfString:@"."];
//由于range.location是NSUInteger类型的,所以不能通过(range.location - ran.location) > 2来判断
if (range.location > ran.location) {
if ([textField.text pathExtension].length > 1) {
NSLog(@"小数点后最多有两位小数");
return NO;
}
}
}
}
return YES;
}
END
网友评论