我的项目常用

UIStoryboard * sb = [UIStoryboard storyboardWithName:@"SpecialMerchantStoryboard" bundle:nil];

SpActDetailViewController *toCtrol = [sb instantiateViewControllerWithIdentifier:@"SpActDetailViewController"];

[self.navigationController pushViewController:toCtrol animated:YES];


#import "NormalMethod.h"


#pragma mark - PCH 文件设置

$(SRCROOT)/nationalFitness/BaseClasses/PublicDefine.h

//A better version of NSLog  打印带有更多信息

#define NSLog(format, ...) do { \

fprintf(stderr, "<%s : %d> %s\n", \

[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], \

__LINE__, __func__); \

(NSLog)((format), ##__VA_ARGS__); \

fprintf(stderr, "-------\n"); \

} while (0)

// DLog 打印出方法名

#ifdef DEBUG

#   define DLog(format, ...) NSLog((@"%s [Line %d]:\n %s = " format), __PRETTY_FUNCTION__, __LINE__, #__VA_ARGS__, ##__VA_ARGS__);

#else

#   define DLog(...)

#endif


//方法1

//手动忽略警告⚠️

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wc++11-narrowing"

//代码

#pragma clang diagnostic pop

//方法二

在 target中build phases中搜索报错的文件 后面加入忽略警告的代码 -Wc++11-narrowing

//方法三

在 other warning flags 中加入忽略代码 -Wc++11-narrowing

//podfile中 加入下面代码 pod的三方不显示任何报警

inhibit_all_warnings!


//头

#define degressToRadius(ang) (M_PI*(ang)/180.0f) //把角度转换成PI的方式

@implementation NormalMethod


@property(nonatomic,strong)NSString *priceText;

@property(nonatomic)BOOL ret;

@property (nonatomic, strong) testEntity *entity;

@property(nonatomic,retain)UIColor *messageSecColor;

-(void)setEntity:(testEntity *)entity{}

@property(nonatomic,copy)NSArray *picPathArr;


bounces



#pragma mark - 宏



UIColorFromRGB(0x8a8a8a);

kPLUS_SCALE_X(<#x#>)


#define myCarFootViewHeight   kPLUS_SCALE_X(200.0f)


#define kHomeButtonCellHeight 145.0f

//设置navigationController 基点从下面左上角算起

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    //设置navigationController no基点从下面左上角算起

    //translucent 是否设置导航栏透明

    [[UINavigationBar appearance] setTranslucent:NO];

    self.navigationController.navigationBar.translucent = NO;

}

#pragma mark - 图片不变形

footView_.titleImage.contentMode = UIViewContentModeScaleAspectFit;


#pragma - mark 代理

<UITableViewDelegate,UITableViewDataSource>


#pragma mark - 设置字体

phoneTextF_.font = [UIFont fontWithName:@"Avenir-Book" size:16];


#pragma mark - 获取window

UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];


#pragma mark - 约束拉成属性进行赋值

headView_.autoPayH.constant = stopServiceHeight/3 * 2;

#pragma mark - CCX动画效果

[self.view.superview setTransitionAnimationType:(CCXTransitionAnimationTypeOglFilp) toward:(CCXTransitionAnimationTowardFromRight) duration:0.5];

#pragma mark - 加载图片 

#import "UIButton+WebCache.h" #import "UIImageView+WebCache.h"

[titleImageV sd_setImageWithURL:[NSURL URLWithString:entity.imgBigUrl] placeholderImage:[UIImage imageNamed:placeholderImge]];

#pragma mark - 数据 本地获取

{

NSMutableArray *arrayS_;

}

//数据 本地获取

arrayS_ = [NSMutableArray new];

NSArray *arrayPrice = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayPrice"];

NSArray *arrayPic = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayPic"];

NSArray *arrayTitle = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayTitle"];

NSArray *arrayAddress = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayAddress"];

NSArray *arrayTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayTime"];

for (int i=0; i<arrayPrice.count; i++) {

    testEntity *entity = [testEntity new];

    entity.price = arrayPrice[i];

    entity.address = arrayAddress[i];

    entity.imgBigUrl = arrayPic[i];

    entity.homepicPath = arrayPic[i];

    entity.title = arrayTitle[i];

    entity.showTime = arrayTime[i];

    [arrayS_ addObject:entity];

}

#pragma mark - 设置UIBarButtonItem返回

UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 34)];

[backBtn setImage:[UIImage imageNamed:@"everyday1_return"] forState:UIControlStateNormal];

[backBtn addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];

self.navigationItem.leftBarButtonItem = backButtonItem;

- (void)backClicked

{

    [self.navigationController popViewControllerAnimated:YES];

}

#pragma mark - 设置UIBarButtonItem 右侧确定

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.frame = CGRectMake(0, 0, 40, 30);

button.titleLabel.font = [UIFont systemFontOfSize:15];

[button setTitle:@"确定" forState:UIControlStateNormal];

[button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];

[button addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView: button];

self.navigationItem.rightBarButtonItem = item;

-(void)sureButtonClick{

    

}


#import "CCZTableButton.h"

//add菜单

CCZTableButton *addShopTableV_;

//更多 图片

UIButton *AddBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 34)];

[AddBtn setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];

[AddBtn addTarget:self action:@selector(AddClicked) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *AddBtnItem = [[UIBarButtonItem alloc]initWithCustomView:AddBtn];

self.navigationItem.rightBarButtonItem = AddBtnItem;

- (void)AddClicked

{

    //菜单

    [addShopTableV_ show];

}


//当列表过多 需要设置可拉时

// joe修改

//用于计算tableview高度

@property (nonatomic, assign) CGFloat topHeight;


//init中

self.topHeight = frame.origin.y;


- (void)updateTableAndFrame {

    // 重新布局tableview

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _size.width, cellHeight * self.itemsArr.count + CCZARROW_VHEIGHT);

    self.mainTableView.frame = CGRectMake(0, CCZARROW_VHEIGHT, _size.width, cellHeight * self.itemsArr.count);

    

    if (cellHeight * self.itemsArr.count > SCREEN_HEIGHT - self.topHeight) {

        self.mainTableView.frame = CGRectMake(0, CCZARROW_VHEIGHT, _size.width, SCREEN_HEIGHT - self.topHeight - 64 + 49);

    }

    [self.mainTableView reloadData];

    

    self.transform = CGAffineTransformMakeScale(0, 0);

}


#pragma mark - 初始化下拉菜单tableview

-(void)initAboutCCZTableV{

#pragma mark - 右上角菜单

    addShopTableV_ = [[CCZTableButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/5*2, 54, SCREEN_WIDTH/5*3 - 5, 0) CellHeight:50];

    addShopTableV_.TitleImageArr = @[@"提问",@"筛选"];

    addShopTableV_.offsetXOfArrow = SCREEN_WIDTH;

    addShopTableV_.wannaToClickTempToDissmiss = YES;

    addShopTableV_.CellBackColor = UIColorFromRGB(0x15597E);

    addShopTableV_.CellTextColor = [UIColor whiteColor];

    [addShopTableV_ addItems:@[@"我要提问",@"条件筛选"]];

    [addShopTableV_ selectedAtIndexHandle:^(NSUInteger index, NSString *itemName) {

        if (index == 0) {

            UIStoryboard * sb = [UIStoryboard storyboardWithName:@"ProblemFeedBackStoryboard" bundle:nil];

            MyQuestionViewController *toCtrol = [sb instantiateViewControllerWithIdentifier:@"MyQuestionViewController"];

            [self.navigationController pushViewController:toCtrol animated:YES];

        }else if (index == 1){

            

        }

    }];

}



#pragma mark - 从cell中跳转storyboard

//跳转storyboard

UIStoryboard *st = [UIStoryboard storyboardWithName:@"StopServiceStoryboard" bundle:nil];

addCarViewController *vc = [st instantiateViewControllerWithIdentifier:@"MyCarViewController"];

[[KeepAppBox viewController:self].navigationController pushViewController:vc animated:YES];

#pragma mark -加载xibCell

//加载xibCell

static NSString* cellIdentifier = @"stopServiceTableViewCell";

stopServiceTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil) {

    cell = [[[NSBundle mainBundle]loadNibNamed:@"stopServiceTableViewCell" owner:nil options:nil]firstObject];

}

cell.selectionStyle = UITableViewCellSelectionStyleNone;

return cell;



//本地数据获取 prepare结束需要 调用主线程进行刷新

dispatch_sync(dispatch_get_main_queue(), ^(void) {

    [self doneLoadingTableViewData];

});


dispatch_async(dispatch_get_main_queue(), ^{

    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

    UIViewController *currentVC = [NFMyManage getCurrentVCFrom:rootViewController];

    if ([currentVC isKindOfClass:[LoginViewController class]]) {

        

    }

});



//线程等待

dispatch_group_async

dispatch_group_sync


//方法1

dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{

    

});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{

    [self.chatTableView reloadData];

    [self tableViewScrollToBottomOffSet:0 IsNeedAnimal:NO];

});

//方法二 如果有for循环。将enter、leave房for里面

dispatch_group_t group = dispatch_group_create();

//这里需要调用串行队列 因为这里就是为了使用多线程处理数据库操作 而调用这个操作需要使用串行

dispatch_sync(dispatch_get_global_queue(0, 0), ^{

    dispatch_group_enter(group);

    // 任务代码i 假定任务 是异步执行block回调

    

    // block 回调执行

    dispatch_group_leave(group);

    // block 回调执行

});

//这里最好 sleep 1秒,因为如果不sleep 那么当 dispatch_get_global_queue中的group线程还没生效 主线程已经到

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

dispatch_sync(dispatch_get_main_queue(), ^{

    // 主线程处理

});


//构建全局线程等待

dispatch_group_t group;

group = dispatch_group_create();


dispatch_group_enter(group);

dispatch_sync(dispatch_get_global_queue(0, 0), ^{

    for (int i = 0; i<10; i++) {

        NSLog(@"&&&&&&&&&");

    }

    dispatch_group_leave(group);

});


dispatch_async(dispatch_get_global_queue(0, 0), ^{

    for (int i = 0; i<10000; i++) {

        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

        NSLog(@"***************************");

    }

});




#pragma mark - 调用主线程

dispatch_async(dispatch_get_main_queue(), ^{

    [UIView animateWithDuration:3 animations:^{

        redL.frame = CGRectMake(0, 0, proLabel.frame.size.width * 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount, 5);

    }];

});


#pragma mark -多线程创建[主线程]

dispatch_queue_t queue = dispatch_queue_create("JoeQueue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^(void) {

    

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        

    });

});


dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        

    });

});


//全局线程

//QOS_CLASS_USER_INTERACTIVE 0x21,              用户交互(希望尽快完成,用户对结果很期望,不要放太耗时操作)

//QOS_CLASS_USER_INITIATED 0x19,                用户期望(不要放太耗时操作)

//QOS_CLASS_UTILITY 0x11,                        实用工具(耗时操作,可以使用这个选项)

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{

});

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{

    [[FLStatusBarHUD shareStatusBar] fl_showCustomView:popView atView:currentVC.view animateDirection:type autoDismiss:_flag];

    //搜索栏-拷贝 设置背景图片

    [FLStatusBarHUD shareStatusBar].backgroundImage = [UIImage imageNamed:@"登陆确认button"];

});


//执行一次

static dispatch_once_t oneToken;

dispatch_once(&oneToken, ^{

    NSLog(@"当前任务所在线程%@是否在主线程%d",[NSThread currentThread],[NSThread isMainThread]);

    NSLog(@"我只执行一次");

});


#pragma mark- 屏幕接收触碰事件监控

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    for (UITextField *textField in self.view.subviews) {

        [textField resignFirstResponder];

    }

}

//点击界面隐藏键盘

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    [self.view endEditing:YES];

}

    static dispatch_once_t oneToken;

    dispatch_once(&oneToken, ^{

        NSLog(@"当前任务所在线程%@是否在主线程%d",[NSThread currentThread],[NSThread isMainThread]);

        NSLog(@"我只执行一次");

    });


#pragma - mark 将某个tableview 经过动画缩小

//将某个tableview 经过动画缩小到右上角一点

tableView.transform = CGAffineTransformMakeScale(0.000001, 0.0001);



// 提交界面

#pragma mark - 提交订单 footview

// 提交订单view

VenuesPayView *payView_;



payView_ = [[VenuesPayView alloc]init];

payView_.view.frame = CGRectMake(0, SCREEN_HEIGHT - 44, SCREEN_WIDTH, 44);

[payView_.payBtn addTarget:self action:@selector(submitoOrders) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:payView_.view];


// //点击支付

- (void)submitoOrders{

    SubVenuesOrdersViewController *vc = [[SubVenuesOrdersViewController alloc]init];

    if (selectArr_.count == 0) {

        [SVProgressHUD showInfoWithStatus:@"没有可支付的订单"];

        return;

    }else if (!self.lastPath){

        [SVProgressHUD showInfoWithStatus:@"请选择支付方式"];

        return;

    }

    vc.orderArr = selectArr_;

    //    vc.venuesID = self.venuesID;

    //    vc.isFromTime = YES;

    //    vc.venuesName = self.venuesName;

    vc.totalPrice = 10.0;

    venueTicketbookEntity *entity = [venueTicketbookEntity new];

    entity.perperPrice = @"10.0";

    vc.ticketEntity = entity;

    //    vc.dateEntity = dateEntity_;

    //    vc.orgCode = _orgCode;

    [self.navigationController pushViewController:vc animated:YES];

    

    

}

#pragma mark - 验证码定时器进阶

#import "HCDTimer.h"

@property(nonatomic,strong)HCDTimer *timer;

{

    //秒

    int secTime_;

    BOOL notFirstCome_; //当需要显示重新获取时候用到 一般直接设置为重新获取

}

- (IBAction)getCodeClick:(id)sender {

    secTime_ = 59;

    [getCodeBtn setTitle:[NSString stringWithFormat:@"%dS",secTime_] forState:UIControlStateNormal];

    self.timer = [HCDTimer repeatingTimerWithTimeInterval:1 block:^{

        secTime_--;

        if (secTime_ == 0)

        {

            [self.timer invalidate];

            [getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];

        }

        else

        {SGPhoto

            [getCodeBtn setTitle:[NSString stringWithFormat:@"%dS",secTime_] forState:UIControlStateNormal];

        }

    }];


}


#pragma mark - 验证码定时器

{

    NSTimer * timer_;

    //秒

    int secTime_;

    BOOL notFirstCome_;

}



- (IBAction)getCodeClick:(id)sender {

    if (!timer_) {

        secTime_ = 59;

        timer_ =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeBegin) userInfo:self repeats:YES];

        [getCodeBtn setTitle:[NSString stringWithFormat:@"%dS",secTime_] forState:UIControlStateNormal];

    }

}


- (void)timeBegin

{

    secTime_ --;

    if (secTime_ == 0)

    {

        [getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];

        [timer_ invalidate];

        timer_ = nil;

    }

    else

    {

        [getCodeBtn setTitle:[NSString stringWithFormat:@"%dS",secTime_] forState:UIControlStateNormal];

    }

}


- (IBAction)sureBtnClick:(id)sender {

    if (markBtn.selected) {

        

    }else{

        [SVProgressHUD showInfoWithStatus:@"请阅读服务协议"];

    }

    

}


#pragma mark - 验证码倒计时block版本

//验证码倒计时

-(void)startTime{

    __block int timeout= 59; //倒计时时间

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行

    dispatch_source_set_event_handler(_timer, ^{

        if(timeout<=0){ //倒计时结束,关闭

            dispatch_source_cancel(_timer);

            dispatch_async(dispatch_get_main_queue(), ^{

                //设置界面的按钮显示 根据自己需求设置

                [_codeBtton setTitle:@"获取验证码" forState:UIControlStateNormal];

                _codeBtton.userInteractionEnabled = YES;

            });

        }else{

            //            int minutes = timeout / 60;

            int seconds = timeout % 60;

            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];

            dispatch_async(dispatch_get_main_queue(), ^{

                //设置界面的按钮显示 根据自己需求设置

                [UIView beginAnimations:nil context:nil];

                [UIView setAnimationDuration:1];

                [_codeBtton setTitle:[NSString stringWithFormat:@"%@秒重发",strTime] forState:UIControlStateNormal];

                [UIView commitAnimations];

                _codeBtton.userInteractionEnabled = NO;

            });

            timeout--;

        }

    });

    dispatch_resume(_timer);

}



#pragma - mark 支付定时15分钟

{

    //支付剩余时间Lab

    @property (nonatomic,strong)UILabel  *surplusTime;

    @property (nonatomic,assign)NSTimer *timer;

}


didload{

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];

    view.backgroundColor = [UIColor lightGrayColor];

    view = [self tableViewheader];

    [self.view addSubview:view];

}


#pragma mark - 获取支付倒计时

- (UILabel *)newILabel:(UILabel *)label

{

    label = [[UILabel alloc] init];

    return label;

}


//表头上的支付剩余时间

- (UIView *)tableViewheader

{

    if (_totalSec)

    {

        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];

        header.backgroundColor = [UIColor colorWithRed:243/255.0 green:185/255.0 blue:46/255.0 alpha:1];

        //标题上的支付剩余时间

        _surplusTime = [self newILabel:_surplusTime];

        _surplusTime.frame = CGRectMake(header.bounds.size.width/2-90, 5, 180, 20);

        _surplusTime.textAlignment =  NSTextAlignmentCenter ;

        _surplusTime.textColor = [UIColor whiteColor];

        _surplusTime.font = [UIFont systemFontOfSize:13];

        [header addSubview:_surplusTime];

        int sec = ((int)_totalSec)%(60 * 60)/60;

        int hour = ((int)_totalSec) % 60;

        if (_totalSec <= 0)

        {

            _surplusTime.text = @"订单已超时!";

            return header;

        }

        

        _sec = hour;

        _hour = sec;

    }

    

    if ((_sec + _hour) > 0)

    {

        

    }

    else

    {

        _sec = 59;

        _hour = 14;

    }

    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];

    header.backgroundColor = [UIColor colorWithRed:243/255.0 green:185/255.0 blue:46/255.0 alpha:1];

    //标题上的支付剩余时间

    _surplusTime = [self newILabel:_surplusTime];

    _surplusTime.frame = CGRectMake(header.bounds.size.width/2-90, 5, 180, 20);

    _surplusTime.text = [NSString stringWithFormat:@"支付剩余时间:%@:%@",@(_hour),@(_sec)];

    _surplusTime.textAlignment =  NSTextAlignmentCenter ;

    _surplusTime.textColor = [UIColor whiteColor];

    _surplusTime.font = [UIFont systemFontOfSize:13];

    [header addSubview:_surplusTime];

    _timer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];

    

    return header;

}


- (void)onTimer:(NSTimer *)timer

{

    if (_sec != 0)

    {

        _sec-= 1;

    }

    else

    {

        _sec = 59;

        _hour = _hour - 1;

    }

    _surplusTime.text = [NSString stringWithFormat:@"支付剩余时间:%@:%@",@(_hour),@(_sec)];

    if (_hour < 0)

    {

        [timer invalidate];

        timer = nil;

        _surplusTime.text = @"订单已超时!";

    }

}


#pragma mark - //弹出确定框

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认解除" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *actionCannel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    return ;

}];

UIAlertAction *actionSure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

    NSArray *carinfo = [NSArray arrayWithObjects:colorT,card, nil];

    [self.delegate addCar:carinfo];

    [self.navigationController popViewControllerAnimated:YES];

}];

[alertController addAction:actionSure];

[alertController addAction:actionCannel];

[self presentViewController:alertController animated:YES completion:nil];


#pragma mark - //弹出框自定义带图片

#import "PopView.h"

//有图

PopView *popV = [[PopView alloc] initWithFrame:self.view.bounds imageName:@"红色感叹号" message:@"您确定要解除绑定吗" isNeedCancel:YES sureBlock:^(BOOL sureBlock) {

    if (sureBlock) {

        //确定按钮

    }else{

        //取消

        

    }

}];

[self.view addSubview:popV];

//没图

PopView *popV = [[PopView alloc] initWithFrame:self.view.bounds message:@"是否确认取消自动付" isNeedCancel:YES isSureBlock:^(BOOL sureBlock) {

    if (sureBlock) {                //确认

        

    }else{                          //取消

    }

}];

//[popV setSecCancelColor:UIColorFromRGB(0x1E8DC9)];

//[popV setSecMessageColor:MainColor];

[self.view addSubview:popV];

//没图

PopView *popV = [[PopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 40, SCREEN_WIDTH/3*2) title:@"审核页面" message:@"您提交的信息需要系统审核,请耐心等待..." isNeedCancel:NO isSureBlock:^(BOOL sureBlock) {

    [self.navigationController popViewControllerAnimated:YES];

}];

[popV setSecTitleBackColor:UIColorFromRGB(0x47B0EB)];

[popV setSecSureColor:UIColorFromRGB(0x47B0EB)];

[popV setSecMessageColor:UIColorFromRGB(0x666666)];

addFromShopTableV.scrollEnabled = NO;

[self.view addSubview:popV];


#pragma mark - //弹出框自定义带tableview

popProTableV = [[PopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 50, SCREEN_WIDTH/3*2) message:@"工作季度选择" CellArrar:@[@"VACS",@"Intel项目"] isSureBlock:^(BOOL sureBlock,NSInteger index) {

    if (sureBlock) {

    }else{

    }

}];

popProTableV.isOnlyOne = YES;

[self.view addSubview:popV_];


#pragma mark - 支付界面

self.testEntity.date = @"10.1";

self.testEntity.payName = @"奥体";

self.testEntity.title = @"奥体";

self.testEntity.price = [NSString stringWithFormat:@"%f",price_];

self.testEntity.discount = 0.95;



#pragma mark - HomeWeatherViewController

{

    HomeWeatherViewController * weatherVc_;

    

}

weatherVc_ = [[HomeWeatherViewController alloc] init];

weatherVc_.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, kHomeWeatherHeight);

homeTableView.tableHeaderView = weatherVc_.view;

//prepareData 中进行赋值,set方法中取出数组中的testEntity类型的实体 取出pic和title

weatherVc_.homeFoucesArr = arrayF;


#pragma mark - 星级设置 星星

#import "starView.h" type 为1 男。type 为2。女 3 为 金色

starView *starr = [[starView alloc] initWithFrame:CGRectMake(0, 0, starViewWidth(3, 8), 50) STARGAP:3 STARHW:8 TYPE:type];

[starr setStarValue:starValue];

//starView_为xib中的控件

[starView_ addSubview:starr];


//实例:在cellForRowAtIndexPath中,通过cell公开的一个set方法value是星级,type是星星的样式

// 在xib中拖入一个view,或者线创建staview类,然后取差不多的数值,starViewWidth(3, 8)中,3为星星之间的间距,8为星星高度 ,二view的高度可以设置为刚好星星的高度。后面的gap 就是为了传过去确切的数值,其实可以直接传过去两个gap,但还是得传高度,所以就一起传过去了。

{cell.selectionStyle = UITableViewCellSelectionStyleNone;

//根据下发数据,type判断是男还是女 男是1 女是2 普通的就是0

[cell setStarValue:3.5 TYPE:1];

}

//cell中具体调用starView类 对星星view进行具体化设置

    -(void)setStarValue:(CGFloat)starValue TYPE:(int)type{

        // (30-20)/2 俯视图的高度上30,starview的高度是20,所以/2可以让她剧中

        starView *starr = [[starView alloc] initWithFrame:CGRectMake(0, 0, starViewWidth(3, 8), 50) STARGAP:3 STARHW:8 TYPE:type];

        [starr setStarValue:starValue];

        [starView_ addSubview:starr];

    }

}


#pragma mark  - 点击设置星级

starView *starV = [[starView alloc] initWithFrame:CGRectMake(0, 0, 200, 40) TYPE:3 clickBlock:^(NSInteger index) {

}];

[starrV addSubview:starV];



#pragma mark - UIAlertController 弹提示框

//初始化

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您正在使用 UIAlertController" preferredStyle:UIAlertControllerStyleAlert];

//创建action 添加到alertController上 可根据UIAlertActionStyleDefault创建不通的alertAction

UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

    //回调

    // 模态视图,使用dismiss 隐藏

    [alertController dismissViewControllerAnimated:YES completion:nil];

}];

UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

    [alertController dismissViewControllerAnimated:YES completion:nil];

}];

//往alertViewController上添加alertAction

[alertController addAction:action1];

[alertController addAction:action2];

//呈现

[self presentViewController:alertController animated:YES completion:nil];


#pragma mark - 日历

//日历

//拖进GFCalendar 日历库 包含 #import "GFCalendar.h"

//然后在initUI中

CGFloat width = self.view.bounds.size.width - 20.0;

CGPoint origin = CGPointMake(10.0, 64.0 + 70.0);

GFCalendarView *calendar = [[GFCalendarView alloc] initWithFrameOrigin:origin width:width];

// 点击某一天的回调

calendar.didSelectDayHandler = ^(NSInteger year, NSInteger month, NSInteger day) {

    

    //        PushedViewController *pvc = [[PushedViewController alloc] init];

    //        pvc.title = [NSString stringWithFormat:@"%ld年%ld月%ld日", year, month, day];

    //        [self.navigationController pushViewController:pvc animated:YES];

};

[self.view addSubview:calendar];


#pragma mark - //push segue to设置

//选中storyboard中 controllerA 黄色的按钮右击

//Triggered segues 关联另外一个controllerB,然后在左边设置identifier

//然后在A中在想要跳转到B的地方写下面代码

[self performSegueWithIdentifier:@"inRegDataSeg" sender:nil];


#pragma mark - 出生日期pickerDate

//首先拉入 DQBirthTool【出生日期】,Masonry两个库,并在DQBirthDateView头文件中设置 #import "Masonry.h"

#import "DQBirthDateView.h"

#import “DQAgeModel.h"

//【DQconstellationView 该类是实现选择星座的】

<DQBirthDateViewDelegate>

@property (nonatomic, strong) DQBirthDateView *DQBirthView;

viewDidLoad{

    self.DQBirthView = [DQBirthDateView new];

    self.DQBirthView.delegate = self;

}

//按钮点击弹出选择框

- (IBAction)buff:(id)sender {

    

    [self.DQBirthView startAnimationFunction];

}

//点击选中哪一行 的代理方法 【选完日期后确定后返回到页面后对日期进行承接】

- (void)clickDQBirthDateViewEnsureBtnActionAgeModel:(DQAgeModel *)ageModel andConstellation:(NSString *)str{

    NSInteger age = [CalculateTool calculateNowAge:ageModel];

    self.ageLab.text = [NSString stringWithFormat:@"%@年 %@月 %@日 %zd岁",ageModel.year,ageModel.month,ageModel.day,age];

    self.ConstellationLab.text = str;

}


#pragma mark - 让textfirld放弃第一响应者

for (UITextField *textField in self.view.subviews) {

    [textField resignFirstResponder];

}

-(void)resignResponder{

    [nameTextfield_ resignFirstResponder];

    [phoneTextfield_ resignFirstResponder];

    [beizhuTextfield_ resignFirstResponder];

}

-(void)viewWillDisappear:(BOOL)animated{

    [self resignResponder];

}

[UIView animateWithDuration:0.2 animations:^{

    _pick.frame = CGRectMake(0, SCREEN_HEIGHT - 150, self.view.frame.size.width, 150);

} completion:^(BOOL finished) {

    

    

}];

#pragma mark - 为屏幕填上一个背影透明的

UIView * backgroundView;

backgroundView.backgroundColor = [UIColor colorWithHue:0

                                            saturation:0

                                            brightness:0 alpha:0.1]; //好看的灰色背景

UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];

backgroundView = [[UIView alloc] initWithFrame:win.bounds];

[win addSubview:backgroundView];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackgroundClickk)];

[backgroundView addGestureRecognizer:tap];


-(void)tapBackgroundClickk{

    [UIView animateWithDuration:0.2 animations:^{

        //将某个tableview 经过动画缩小到右上角一点

        //        tableView.transform = CGAffineTransformMakeScale(0.000001, 0.0001);

    } completion:^(BOOL finished) {

        [backgroundView removeFromSuperview];

    }];

}


#pragma mark - 为屏幕填上一个背影带浅灰色的

//最底下clear 背景

UIView *backV_;

//第二层 半透明背景

UIView *secBackV;


backV_ = [[UIView alloc] initWithFrame:self.view.bounds];

backV_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

backV_.backgroundColor = [UIColor clearColor];

UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];

[win addSubview:backV_];


secBackV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

secBackV.backgroundColor = [UIColor blackColor];

secBackV.alpha = 0.5;

[backV_ addSubview:secBackV];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackgroundClickk)];

[secBackV addGestureRecognizer:tap];

//将需要add的视图添加上去。

[backV_ addSubview:pickV];

-(void)tapBackgroundClickk{

    [UIView animateWithDuration:0.2 animations:^{

        //将某个tableview 经过动画缩小到右上角一点

        //        tableView.transform = CGAffineTransformMakeScale(0.000001, 0.0001);

    } completion:^(BOOL finished) {

        [backV_ removeFromSuperview];

    }];

}

#pragma mark - 菜单栏

//拉入CCZTableButton类 #import "CCZTableButton.h"

CCZTableButton *priceTableV_;

CCZTableButton *typeTableV_;

//设置价格 类别 按钮

priceBtn_ = [[UIButton alloc] initWithFrame:CGRectMake(0, navigationHeight, SCREEN_WIDTH/2.0, 44)];

priceBtn_.tag = 1;

[priceBtn_ setTitle:@"价格" forState:(UIControlStateNormal)];

[priceBtn_ setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];

[priceBtn_ setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];

[priceBtn_ addTarget:self action:@selector(priceORtype:) forControlEvents:(UIControlEventTouchDown)];

//设置弹出来的tableview

priceTableV_ = [[CCZTableButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(priceBtn_.frame), SCREEN_WIDTH, 0) CellHeight:50];

priceTableV_.offsetXOfArrow = SCREEN_WIDTH;

priceTableV_.wannaToClickTempToDissmiss = NO; //不选cell 界面不消失,省去了一点麻烦

[priceTableV_ addItems:@[@"价格从高到底",@"价格从低到高"]];

[priceTableV_ selectedAtIndexHandle:^(NSUInteger index, NSString *itemName) {

    [self setImageAndBtnNormal];

    NSLog(@"%@",itemName);

}];

-(void)priceORtype:(UIButton *)sender{

//    [self setBtnState:sender];

        [priceTableV_ show];

}

//当点击按钮后 需要button的字体或者图片发生改变

//-(void)setBtnState:(UIButton *)sender{

//    if (sender.tag == 1) {

//        if (sender.selected) {

//            

//        }else {

//            priceImageV_.image = [UIImage imageNamed:@"未标题-1_07-4"];

//            typeImageV_.image = [UIImage imageNamed:@"灰色向下"];

//            sender.selected = YES;

//            UIButton *rightBtn = [self.view viewWithTag:2];

//            rightBtn.selected = NO;

//        }

//}


#pragma mark - 传值

__strong 确保在 Block 内,strongSelf 不会被释放。

总结

在 Block 内如果需要访问 self 的方法、变量,建议使用 weakSelf。

如果在 Block 内需要多次 访问 self,则需要使用 strongSelf。

__weak typeof(self)weakSelf=self;

//strongSelf当然这个必须要明白的是, 这个block里面的strongSelf能够保证里面代码执行完毕的前提是程序能够执行到block, 如果在执行block之前self已经被销毁了, 那么这个block肯定是不会被调用的(block的引用计数已经为0) 当对于全局变量【私有变量】进行赋值时 需要这样,否则不走delloc[疑问?]

__strong typeof(weakSelf)strongSelf=weakSelf;

strongSelf ->

:^{

#pragma mark - 代码块传值

//如果在代码块中使用了外部定义的变量a,当这个变量改变值为b后,代码块中又使用了该变量 则变量值依然是a,如果需要做出改变 则在外部变量前面加上 __block即可

//即在传出方 公开一个方法,这个方法是为了将外面的一个代码块强引用至本地。所以引用方和被引用方的代码块类型必须一样。然后在需要传值的时候,调用本地这个代码块并带入值,这时候,与外面绑定的代码块{}中的代码也就执行了,完成传值。

//我的待办代办  知识库 授权管理 问题反馈 任务管理 客户资料

//void 指传出方需要一个返回值,nsstring指传出到接受方的值 一般前面不需要传值

typedef void (^ReturnTextBlock)(NSString *showText);

@property(nonatomic,copy)ReturnTextBlock returnTextBlock;

-(void)returnText:(ReturnTextBlock)block;

.m

-(void)returnText:(ReturnTextBlock)block{

    self.returnTextBlock = block;

}

-(void)previousPage{

    if (self.returnTextBlock) {

        self.returnTextBlock(_textField.text);

    }

    [self dismissViewControllerAnimated:YES completion:^{

    }];

}

//接收方

[secondVC returnText:^(NSString *showText) {

    _textField.text = showText;

    

}];


-(instancetype)initWithFrame:(CGRect)frame imageName:(NSString *)name message:(NSString *)message isNeedCancel:(BOOL)isNeedCancel sureBlock:(void(^)(BOOL sureBlock))sureBlock{

    if (self) {

        PopFrame_ = frame;

        CGRect rect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

        self = [super initWithFrame:rect];

        isNeedCancel_ = isNeedCancel;

        if (_sure != sureBlock) {

            _sure = nil;

            _sure = sureBlock;

        }

        _imageName = name;

        _message = message;

        

        [self costomView];

        

    }

    return self;

}


#instance 方法中插入代码块

//在h文件中申明

@property(nonatomic,strong)void(^ReturnEveryRowBlock)(NSInteger firstRow,NSInteger secondRow,NSInteger thirdRow);

//在instance方法中同样插入

-(instancetype)initWithFrame:(CGRect)frame FirstCompontArr:(NSArray *)fisrt SecondCompont:(NSArray *)second ThirdCompont:(NSArray *)third forthCompont:(NSArray *)forth rowHeight:(CGFloat)height  ReturnEveryRowBlock:(void(^)(BOOL isSure,NSInteger firstRow,NSInteger secondRow,NSInteger thirdRow,NSInteger forthRow))Block{


#pragma mark - 方法封装代码块

    //创建一个类,写一个方法,可以是instancetype 方法,可以是其他方法,只是单纯的init方法不需要公开,但是许国要加代码块,则必须要公开了

    

    @property(nonatomic,strong)void(^sure)(void); //这是在封装的类的h文件声明的 sure为代码块名字,该代码块类型需要和方法中的代码块类型一样

    

    (void(^)(void)) //这是一个block,第一个viod 是返回类型为空,中间的^后面跟的是代码块的额名字,第二个viod 是传值类型

    

    -(instancetype)initWithFrame:(CGRect)frame imageName:(NSString *)name message:(NSString *)message sureBlock:(void(^)(void))sureBlock{

        if (self) {

            self = [super initWithFrame:frame];

            //进来就将公开的代码块赋值给本地全局变量代码块,方便后面随时调用 实现回调功能。

            if (_sure != sureBlock) {

                _sure = nil;

                _sure = sureBlock;

            }

            _imageName = name;

            _message = message;

            

            [self costomView];

            

        }

        return self;

    }

    

    //在某个点击事件中,调用代码块 实现回调 必须要 __weak self;

    -(void)mySignBtnClick{

        __weak PopView *ws=self;

        [self removeFromSuperview];

        if (ws.sure) {

            ws.sure();

        }

    }

    

#pragma mark - 本界面定义使用代码块

    -(void)getCarInfoFromtextFIsSuccess:(void(^)(BOOL isSuccessBlock))isSuccessBlock{

        void (^block) (BOOL);

        block = isSuccessBlock;

        if (_textF.text.length != 8 || ![_textF.text containsString:@":"]) {

            [SVProgressHUD showInfoWithStatus:@"请输入规定样式车牌号"];

            block(NO);

            return;

        }

        

    }


#pragma mark - 设置代理

@protocol CCXSecondViewControllerDelegate <NSObject>

-(void)sendValue:(NSString *)value;

@end

@property(weak,nonatomic)id<CCXSecondViewControllerDelegate> delegate;

//.m中

[self.delegate sendValue:_textField.text];

//接收方

secondVC.delegate = self;

-(void)sendValue:(NSString *)value{

    _textField.text = value;

}



#pragma mark -  键盘类型设置

_passwordTextField.keyboardType = UIKeyboardTypeNumberPad;


#pragma mark -  通过event 获取到indexpath中的数据 点击选中cell,从而获取cell并改变cell里面的button状态

- (void)searchClick:(UIButton *)button event:(UIEvent *)event

{

    NSSet *touches = [event allTouches];

    UITouch *touch = [touches anyObject];

    CGPoint currentTouchPosition = [touch locationInView:tableView_];

    NSIndexPath *indexPath = [tableView_ indexPathForRowAtPoint:currentTouchPosition];

}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {

        AddressBtnTableViewCell *cell = (AddressBtnTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

        [self selectedPay:cell.selectBtn event:nil];

    }

}

- (void)selectedPay:(UIButton *)sender event:(UIEvent *)event

{

    if (_selectedBtn)

    {

        _selectedBtn.selected = NO;

    }

    if (!sender.selected)

    {

        sender.selected = YES;

        _selectedBtn = sender;

    }

    else

    {

        sender.selected = NO;

    }

}

#pragma mark - 获取cell

NSIndexPath *indexpath = [NSIndexPath indexPathForRow:1 inSection:0];

AddressBtnTableViewCell *cell = (AddressBtnTableViewCell *)[localTableView_ cellForRowAtIndexPath:indexPath];

#pragma - mark 获取,点击cell,执行cell上面的按钮方法

//点击cell,执行cell上面的按钮方法

PaymentOrderCell *cell = (PaymentOrderCell *)[tableView cellForRowAtIndexPath:indexPath];

[self selectedPay:cell.selectedButton event:nil];

#pragma mark - 刷新cell section

NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

//section

NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];

[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

#pragma mark - 删除cell section

[addAddressTableV deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]  withRowAnimation:UITableViewRowAnimationRight];

//section

NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indexPath.section];

[addAddressTableV deleteSections:indexSet withRowAnimation:UITableViewRowAnimationRight];


#pragma mark - scrollChange调用  

#import "ScrollVChanged.h" <ScrollVChangedDelegate>

[[UINavigationBar appearance] setTranslucent:NO]; //didloadview 中 //让self。view 从navigation左下角开始

self.navigationController.navigationBar.translucent = NO;


NSArray *array = @[@"待预约",@"签到",@"已完成",@"已暂停"];

ScrollVChanged *topViews = [[ScrollVChanged alloc] initWithCreateScrollerWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, scrollVlabelH) andChange:array];

topViews.delegate = self;

[self.view addSubview:topViews];


-(void)ScrollChangeClick:(UIButton *)sender{

    testEntity *entity = [arrayS_ objectAtIndex:sender.tag - 1];

    arrayT_ = [NSArray arrayWithObject:entity];

    [myPritiseTableV reloadData];

}

    

#pragma mark - 圆角

    typedef NS_OPTIONS(NSUInteger, UIRectCorner) {

        UIRectCornerTopLeft     = 1 << 0,

        UIRectCornerTopRight    = 1 << 1,

        UIRectCornerBottomLeft  = 1 << 2,

        UIRectCornerBottomRight = 1 << 3,

        UIRectCornerAllCorners  = ~0UL

    };

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:sender.bounds byRoundingCorners:a | b | c | d cornerRadii:CGSizeMake(roundW, roundW)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    maskLayer.frame = sender.bounds;

    maskLayer.path = maskPath.CGPath;

    sender.layer.mask = maskLayer;


#pragma mark - 设置不规则圆角 view  button

-(void)setViewRound:(UIView *)view TopLeft:(BOOL)TopLeft TopRight:(BOOL)TopRight BottomLeft:(BOOL)BottomLeft BottomRight:(BOOL)BottomRight cornerRadii:(CGFloat)roundW{

    UIRectCorner a;

    UIRectCorner b;

    UIRectCorner c;

    UIRectCorner d;

    if (TopLeft) {

        a = TopLeft;

    }else if (TopRight){

        b = TopRight;

    }else if (BottomLeft){

        c = BottomLeft;

    }else if (BottomRight){

        d = BottomRight;

    }

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:a | b | c | d cornerRadii:CGSizeMake(roundW, roundW)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    maskLayer.frame = view.bounds;

    maskLayer.path = maskPath.CGPath;

    view.layer.mask = maskLayer;

}


-(void)setBtnRound:(UIButton *)sender TopLeft:(BOOL)TopLeft TopRight:(BOOL)TopRight BottomLeft:(BOOL)BottomLeft BottomRight:(BOOL)BottomRight cornerRadii:(CGFloat)roundW{

    UIRectCorner a;

    UIRectCorner b;

    UIRectCorner c;

    UIRectCorner d;

    if (TopLeft) {

        a = TopLeft;

    }else if (TopRight){

        b = TopRight;

    }else if (BottomLeft){

        c = BottomLeft;

    }else if (BottomRight){

        d = BottomRight;

    }

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:sender.bounds byRoundingCorners:a | b | c | d cornerRadii:CGSizeMake(roundW, roundW)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    maskLayer.frame = sender.bounds;

    maskLayer.path = maskPath.CGPath;

    sender.layer.mask = maskLayer;

}


#pragma mark - 绘制直线

UIBezierPath *path = [UIBezierPath bezierPath];

[path moveToPoint:CGPointMake(50, 0)];

[path addLineToPoint:CGPointMake(100, 0)];

[path addLineToPoint:CGPointMake(75, 100)];

// 最后的闭合线是可以通过调用closePath方法来自动生成的,也可以调用-addLineToPoint:方法来添加

//  [path addLineToPoint:CGPointMake(50, 0)];

[path closePath];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

maskLayer.frame = vieww.bounds;

maskLayer.path = path.CGPath;

vieww.layer.mask = maskLayer;

#pragma mark - 绘制两段曲线 [进过裁剪后,保留下面三点之间的区域]

[path moveToPoint:CGPointMake(0, 0)];

[path addQuadCurveToPoint:CGPointMake(300,10)

             controlPoint:CGPointMake(200, 200)];



#pragma mark - 敬请期待

NFbaseViewController *baseViewCtrol = [[NFbaseViewController alloc] init];

[baseViewCtrol showAlertHud:CGPointZero withStr:@"更多精彩敬请期待!"];

_label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height/3, self.view.frame.size.width, self.view.frame.size.width/3)];

_label.text = @"更多精彩敬请期待";

_label.textColor = [UIColor lightGrayColor];

_label.font = [UIFont systemFontOfSize:30];

_label.textAlignment = NSTextAlignmentCenter;

[self.view addSubview:_label];

NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(showHUD) userInfo:nil repeats:YES];

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];


    [_timer setFireDate:[NSDate distantFuture]];

    [_timer setFireDate:[NSDate distantPast]];

    

-(void)showHUD{

    [UIView animateWithDuration:1 animations:^{

        _label.alpha = 0.0;

    } completion:^(BOOL finished) {

        [self performSelector:@selector(showHUDD) withObject:nil afterDelay:0];

    }];

}

-(void)showHUDD{

    [UIView animateWithDuration:1 animations:^{

        _label.alpha = 1.0;

    } completion:^(BOOL finished) {

        

    }];

}




#pragma mark - tabbar UISearchBarBackground 去除灰色

for (UIView *view in self.searchBar.subviews) {

    // for before iOS7.0

    if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {

        [view removeFromSuperview];

        break;

    }

    // for later iOS7.0(include)

    if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {

        [[view.subviews objectAtIndex:0] removeFromSuperview];

        break;

    }

}

//获取searchbar上面 textfield 指针

UITextField *txfSearchField = [self.searchBar valueForKey:@"_searchField"];

//设置cannel按钮 UINavigationButton

for(id cc in [self.searchBar.subviews[0] subviews])

{

    if([cc isKindOfClass:[UIButton class]])

    {

        UIButton *btn = (UIButton *)cc;

        [btn setTitle:@"aa" forState:(UIControlStateNormal)];

    }

}


#pragma amrk  - 地图

#import <AMapSearchKit/AMapSearchAPI.h> #import <MAMapKit/MAMapKit.h>  


//显示当前位置

//【注意】:showsUserLocation,userTrackingMode 最好在 viewDidAppear中设置。

MAMapView *mapView_;

mapView_ = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.frame.size.height - 60.0f)];

mapView_.delegate = self;

mapView_.userTrackingMode =  MAUserTrackingModeFollow;

mapView_.showsUserLocation = YES;

[mapView_ setZoomLevel:16.5f];

mapView_.showsCompass = NO;

mapView_.showsScale = NO;

mapView_.distanceFilter = 10.0;

mapView_.headingFilter = 90.0;

mapView_.headingFilter = kCLHeadingFilterNone;

[self.view addSubview:mapView_];


//搜索功能 先创建对象,再设置地理位置 名字等 然后add到mapview上去

MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];//创建对象

pointAnnotation.coordinate = CLLocationCoordinate2DMake(32.048901+i*0.001,118.790081+i*0.001);

pointAnnotation.title = [NSString stringWithFormat:@"长江数码大厦%d楼",i];

pointAnnotation.subtitle = [NSString stringWithFormat:@"博微风%d分区",i];

[_mapView addAnnotation:pointAnnotation];


//构造折线数据对象 路线

CLLocationCoordinate2D commonPolylineCoords[4];

commonPolylineCoords[0].latitude = 32.048901;

commonPolylineCoords[0].longitude = 118.790081;


commonPolylineCoords[1].latitude = 32.047903;

commonPolylineCoords[1].longitude = 118.791091;


commonPolylineCoords[2].latitude = 32.042905;

commonPolylineCoords[2].longitude = 118.794101;


commonPolylineCoords[3].latitude = 32.042907;

commonPolylineCoords[3].longitude = 118.795111;

//构造折线对象

MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:4];

//在地图上添加折线对象

[_mapView addOverlay: commonPolyline];


#pragma mark -从cell中跳转到指定的控制器 获取带最近的controller

//方法一

NFbaseViewController *viewCtrol = (NFbaseViewController *)[self viewController];

//UIStoryboard * sb = [UIStoryboard storyboardWithName:@"TicketCard" bundle:nil];

//VipCarBuyPayViewController *toCtrol = [sb instantiateViewControllerWithIdentifier:@"VipCarBuyPayViewController"];

//[viewCtrol.navigationController pushViewController:toCtrol animated:YES];

#pragma mark - 跳转需要获得父类viewctroller

- (UIViewController *)viewController

{

    for (UIView *next = [self superview]; next; next = next.superview)

    {

        UIResponder *nextResponder = [next nextResponder];

        if ([nextResponder isKindOfClass:[UIViewController class]])

        {

            return (UIViewController *)nextResponder;

        }

    }

    return nil;

}

    

//方法二 用单例

[[KeepAppBox viewController:self].navigationController pushViewController:chatVC animated:YES];


#pragma mark -返回root视图 [pop to rootView]

    [[NSNotificationCenter defaultCenter] postNotificationName:kGoto_Home_afterActSuccess object:nil];

    

    //方法3

    UIViewController * viewVC = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 3];

    [self.navigationController popToViewController:viewVC animated:YES];

    //通知中心4

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addFriendCount:) name:@"addFriendCount" object:nil];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"addFriendCount" object:@{@"addFriend":@"1"}];

    //参数

    - (void)connectBreak:(NSNotification *)notifi

    NSDictionary* info = [notifi userInfo];


    int token = 2;

    notify_register_dispatch("homeNotification", &token, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(int token) {

        NSLog(@"receive nofity");

    });

    

    notify_post("homeNotification");

    

    

    

#pragma mark -将group模式下 headview 和section之间的间距除掉

UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.001)];

view.backgroundColor = [UIColor redColor];

ChoseDayTableV_.tableHeaderView = view;

#pragma mark - 分割线

UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 1)];

line.backgroundColor = SecondGray;

[view addSubview:line];




#pragma mark - 如果想要在cell xib的.m中进行跳转和传值。

@property (nonatomic, strong) testEntity *entity;//之后 还需要将实体赋值给全局变量 entity_

// 内存中。每一次cell的创建都是开辟的新的地址,展示的每一个cell都和一块地址绑定,当点击的时候是访问绑定的内存,然后所有的数据调用都默认在该段内存里面寻找。如果进行了跳转并且需要传值的话,当开辟该内存的时候就将可能需要传的值放进来。

-(void)setEntity:(testEntity *)entity{

    entity_ = entity;

    [midBtn setTitle entity.title

}



     

#pragma mark -storyboard 中 静态cell 和动态cell混用

// 环境: 我需要设置一个section中的cell个数载 3 - 5 左右

// 在storyboard 中创建tableview controller,然后设置3个section都为static,第二个section中设置8个cell【尽可能地多一点】【不需要设置identify】。

//然后在viewcontroller 中 设置代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

 if (section == 1) {

     return 4;

 }

 return [super tableView:coachDetailTableV numberOfRowsInSection:section];

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

 if (indexPath.section == 1) {

     return 50;

 }

 return [super tableView:coachDetailTableV heightForRowAtIndexPath:indexPath];

}

 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.section == 1) {

    UITableViewCell *cell = [tableView

                             dequeueReusableCellWithIdentifier:@"OneTicketBuyDetailCellT"];

    return cell;

  }

return [super tableView:coachDetailTableV cellForRowAtIndexPath:indexPath];

}

 


     

     

#pragma mark - 动态高度计算

// NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};

// CGFloat length = [Text boundingRectWithSize:CGSizeMake(JOESIZE.width-2*GAPB, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;

参考洛阳

     - (CGFloat)theShowMoreHeight:(NSString *)theStr

    {

        UILabel *disHeightLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 50.f, 0.0f)];

        [disHeightLab setNumberOfLines:0];

        disHeightLab.font = [UIFont systemFontOfSize:13.0];

        disHeightLab.text = theStr;

        [disHeightLab sizeToFit];

        return disHeightLab.frame.size.height;

    }

#pragma mark - 约束换行

     initUI中

     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};

     CGFloat height = [detailEntity_.storeName boundingRectWithSize:CGSizeMake(JOESIZE.width - 100, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;

     storeNameHeightContant.constant = height+ 1;

     

     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};

     CGFloat length = [detailEntity_.storeAddress boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 125, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;

     length -= 19;

     //计算出来的高度减去label高度20,加上4【上面8个控件 所以有8个锚点0.5】+ 加0.5

     heightForRowAtIndexPath 中

     attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};

     CGFloat height = [detailEntity_.storeName boundingRectWithSize:CGSizeMake(JOESIZE.width - 100, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;

     height -= 19;

     //

     return 330 + height + length;

#pragma mark - shouldChangeCharactersInRange

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

 if (textField.text.length + string.length - range.length >10) {

     return NO;

 }

 actualPriceLabel.text = textField.text;

 return YES;

}

     

#pragma mark - 登陆判断

     -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

         int a = [[NFMyManage new] checkIsHaveNumAndLetter:string];

         if (textField.tag == 11) {

             if (textField.text.length + string.length - range.length >11) {

                 [SVProgressHUD showInfoWithStatus:@"账号不得超过11位"];

                 return NO;

             }

             if (a != 4) {

                 return YES;

             }else{

                 [SVProgressHUD showInfoWithStatus:@"请输入合法帐号"];

                 return NO;

             }

         }

         if (textField.text.length + string.length - range.length > 20) {

             [SVProgressHUD showInfoWithStatus:@"密码不正确"];

             return NO;

         }

         

         if (a != 4) {

             return YES;

         }else{

             [SVProgressHUD showInfoWithStatus:@"密码格式不正确"];

             return NO;

         }

     }

 

//将一个textfield输入框 与一个label关联,实现数字同增减

//actualPriceLabel 为关联的label,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

 if (textField.text.length + string.length - range.length >10) {

     return NO;

 }

 //将输入的金额显示在实付金额中

 if (string.length > 0) {

     if ([actualPriceLabel.text isEqualToString:@"0"]) {

         actualPriceLabel.text = @"";

     }

     NSMutableString *afterAddString = [NSMutableString stringWithString:actualPriceLabel.text];

     [afterAddString insertString:string atIndex:range.location];

     actualPriceLabel.text = afterAddString;

 }else{

     NSMutableString *afterDeleteString = [NSMutableString new];

     afterDeleteString = [NSMutableString stringWithFormat:@"%@",actualPriceLabel.text];

     [afterDeleteString deleteCharactersInRange:range];

     actualPriceLabel.text = afterDeleteString;

     if (actualPriceLabel.text.length == 0) {

         actualPriceLabel.text = @"0";

     }

 }

 return YES;

}

 

#pragma mark - 枚举

     typedef NS_ENUM(NSInteger){

         EditNameType    = 0<<0, //编辑名字

         EditTypeAccount    = 1<<0,//编辑账号

         EditTypePersonalSingature    = 2<<0,//编辑个性签名

         

         

     }EditType;

     

#pragma mark - 实现注册成功选头像的collection效果

     HJCarouselViewLayout 公开的参数{

         枚举NS_ENUM:         //是layout的样式

         initWithAnim       // 选择样式

         itemSize           //item  大小

         visibleCount       // 显示的个数 默认为5个

         scrollDirection    //滑动方向

         index              //当前中间显示的item的index 从0开始

     }

#import "HJCarouselViewLayout.h" collection 布局

//     NSMutableArray * imageArr_;

//     HJCarouselViewLayout * layout;

//     //处于中间图片的index

//     CGFloat index_;

     

//storyboard 和 xib 的设置

//xib中拖入一个collectionV [中间放上一个imageView 可不放,看需求]

//__weak IBOutlet UIImageView *showImageView; //上层显示的图片

//__weak IBOutlet UICollectionView *headCollectionView; //这是CollectionView

//然后 xib 设置一个item

// cell.headImageView //collectionV上面的图片

     typedef NS_ENUM(NSUInteger, HJCarouselAnim) {

         HJCarouselAnimLinear,

         HJCarouselAnimRotary,

         HJCarouselAnimCarousel,

         HJCarouselAnimCarousel1,

         HJCarouselAnimCoverFlow,

     };

#pragma mark - initUI中

UINib * nib = [UINib nibWithNibName:@"HeadCircleCell" bundle:[NSBundle mainBundle]];

[headCollectionView registerNib:nib forCellWithReuseIdentifier:@"HeadCircleCell"];

layout = [[HJCarouselViewLayout alloc] initWithAnim:HJCarouselAnimCarousel];

layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

layout.itemSize = CGSizeMake(80, 80);

headCollectionView.collectionViewLayout = layout;

index_ = 1;


#pragma mark - scrollView delegate

     - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

    {

        showImageView.hidden = YES;

    }

     

     - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

    {

        index_ = layout.index;

        NSInteger index = index_;

        showImageView.image = [UIImage imageNamed:imageArr_[index]];

        showImageView.hidden = NO;

        //    [NFUserEntity shareInstance].smallpicpath = [imageArr_ objectAtIndex:index_];

    }


#pragma mark UICollectionViewDataSource delegate

     

     - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

         NSLog(@"click %ld", (long)indexPath.row);

     }

     

     

     - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

         return [imageArr_ count];

     }

     

     - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

         HeadCircleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HeadCircleCell" forIndexPath:indexPath];

         cell.headImageView.image = [UIImage imageNamed:[imageArr_ objectAtIndex:indexPath.row]];

         

         return cell;

     }

     

     - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

    {

        [self.view endEditing:YES];

    }


#pragma mark - 手势

     

 - (void)addAGesutreRecognizerForYourView

{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesturedDetected:)]; // 手势类型随你喜欢。

    tapGesture.delegate = self;

    [tableV_ addGestureRecognizer:tapGesture];

}

 

 - (void)tapGesturedDetected:(UITapGestureRecognizer *)recognizer

{

    // do something

    [textF_ resignFirstResponder];

}


#pragma mark - label 可点

#import "FMLinkLabel.h"

//如果是xib中的label 则需要继承该类

     @property (weak, nonatomic) IBOutlet FMLinkLabel *label;

     self.label.text = @"呵呵哒 :呵呵呵呵呵呵呵呵额哈哈哈";

     [self.label addClickText:@"呵呵哒 :" attributeds:@{NSForegroundColorAttributeName : [UIColor orangeColor]} transmitBody:(id)@"呵呵哒 被点击了" clickItemBlock:^(id transmitBody) {

        //点击执行事件

        [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", transmitBody] delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil] show];

        

    }];


#pragma mark - 判断是否为合法手机号

[KeepAppBox isValidatePhone:firstTextField.text]


#pragma mark - 性别选择

     //可以是 didselect。也可以是按钮点击

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

 if (indexPath.section == 1) {

     //选择性别

     UIStoryboard *story = [UIStoryboard storyboardWithName:@"NFLoginStoryboard" bundle:nil];

     RegInSexViewController *sexCtrol = [story instantiateViewControllerWithIdentifier:@"RegInSexViewController"];

     //        sexCtrol.isFromSet = YES;

     sexCtrol.fromType = 0;

     sexCtrol.delegate = self;

     [self.navigationController pushViewController:sexCtrol animated:YES];

 }

}


//选择性别的代理方法

-(void)sendSexValue:(NFSex)value{

 if (value == 1) {

     sexLabel.text = @"男";

 }else if (value == 2){

     sexLabel.text = @"女";

 }

}


#pragma mark - 时间获取

NSDate *currentDate = [NSDate date];//获取当前时间,日期

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS"];

NSString *dateString = [dateFormatter stringFromDate:currentDate];

NSLog(@"dateString:%@",dateString);


#pragma mark - 生成多位随机数

     NSInteger a = arc4random()%899999+100000;

     NSDate *currentDate = [NSDate date];//获取当前时间,日期

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

     [dateFormatter setDateFormat:@"YYYYMMddhhmmssSS"];

     NSString *dateString = [dateFormatter stringFromDate:currentDate];

     NSLog(@"dateString:%@",[NSString stringWithFormat:@"%@%ld",dateString,a]);

     

     //生成chatid 日后向服务器索取

     //    NSInteger a = arc4random()%899999+100000;

     //    NSDate *currentDate = [NSDate date];//获取当前时间,日期

     //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

     //    [dateFormatter setDateFormat:@"YYYYMMddhhmmssSS"];

     //    NSString *dateString = [dateFormatter stringFromDate:currentDate];

     //    messagee.chatId = [NSString stringWithFormat:@"%@%ld",dateString,a];

     messagee.chatId = [[data objectForKey:@"messageId"] description];

     

#pragma mark - NSTimeInterval相关

     NSDate *currentDate = [NSDate date];//获取当前时间,日期

     //计算两个 nsdate 差值

     NSTimeInterval time = [currentDate timeIntervalSinceDate:confromTimesp];

     

     //nsdate转NSTimeInterval

     NSTimeInterval interval = [currentDate timeIntervalSince1970];

     

     

     

//如果是设置一个控件入label的位置,从一点到另一点,想要有动画效果。【先写变化后的frame,再动画设置layoutIfNeeded】

     leftContrain.constant = 100

     UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.AllowAnimatedContent, animations: {

        self.view.layoutIfNeeded() //立即实现布局

    }, completion: nil)

//"如果一些变化不想动画 。在动画前执行self.view.layoutIfNeeded()"


#pragma mark - nsinter 转 nsdate

     NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[chatData objectForKey:@"create_time"] integerValue]];

     

#pragma mark - 获取某nsdate 星期几

     NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[chatData objectForKey:@"create_time"] integerValue]];

     NSString *xingqi = [date dayFromWeekday];

#import "CycleScrollView.h" <CycleScrollViewDelegate>

#pragma mark - //带标题的轮播图

@property (strong,nonatomic) CycleScrollView *networkTitleScrollView;

     

if (_networkTitleScrollView == nil) {

 _networkTitleScrollView = [CycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHomeWeatherHeight) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];

 //        _networkTitleScrollView.imageURLStringsGroup = self.networkImageNameAry;

 _networkTitleScrollView.currentPageDotColor = MainColor;

 _networkTitleScrollView.pageDotColor = [UIColor whiteColor];

 _networkTitleScrollView.pageControlBottomOffset = 25;

 // 自定义分页控件小圆标颜色

 //        _networkTitleScrollView.titlesGroup = self.networkTextAry;

 //        _networkTitleScrollView.imageURLStringsGroup = self.networkImageNameAry;

}

homeTableView.tableHeaderView = _networkTitleScrollView;

     

     _networkTitleScrollView.imageURLStringsGroup = picArr;

     _networkTitleScrollView.titlesGroup = titleArr;

     _networkTitleScrollView.placeholderImage = [UIImage imageNamed:@"banner"];

     _networkTitleScrollView.autoScrollTimeInterval = 4.5;

     

     



#pragma mark - 数组排序 [必须有数字]

venArr_ = @[@"01号场",@"02号场",@"03号场"];

venArr_ = [venArr_ sortedArrayUsingSelector:@selector(compare:)];


     

#pragma mark - 正则表达式

“ \d ”匹配一个数字字符。等价于[0-9]。

“ \D”匹配一个非数字字符。等价于[^0-9]。

“ \w ”匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”。

“ \W ”匹配任何非单词字符。等价于“[^A-Za-z0-9_]”。

iOS中书写正则表达式,碰到转义字符,多加一个“\”,例如:全数字字符:@”^\d+$”


 验证用户名和密码

 ^[a-zA-Z]\w{5,15}$


 验证手机号码

 ^1[3|4|5|7|8][0-9]\\d{8}$

 

 只能输入数字

 ^[0-9]*$

//正则车牌号

     if (![[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[\u4e00-\u9fa5]{1}[A-Z]{1}[^a-zA-Z\u4e00-\u9fa50-9]{1}[0-9A-Z]{5}"] evaluateWithObject:_textF.text]) {

         [SVProgressHUD showInfoWithStatus:@"请输入规定样式车牌号"];

         return;

     }

     

#pragma mark - coreData 使用

#import "MyOwnCoreData+CoreDataProperties.h"

    {

        NSMutableArray *cacheDataArr_;

        

    }

@property(nonatomic,strong)NSManagedObjectContext *context;


//setupContext 中 数据库路径换成新的【APPDelete 中数据库名字】

 -(void)setupContext

{

    //    1.创建上下文

    NSManagedObjectContext *context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];

    //    2. 关联Company.xcdatamodeld模型文件

    //    传一个nil会把buddle下的所有模型文件关联起来

    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];

    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];

    //存储数据库的名字

    NSError *error = nil ;

    //获取Document的路径

    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject];

    //数据库路径

    NSString *sqlitePath = [docPath stringByAppendingPathComponent:@"coredatePackage.sqlite"];

    NSLog(@"-----------path-------%@",sqlitePath);

    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];

    

    context.persistentStoreCoordinator = store ;

    self.context = context ;

}


//     checkMember 中

//     将实体名字换成新的 【plist中的实体名字

//     【checkMember 中 ,设置谓词,将查出的数据根据某字段进行排序】

//     将for循环中的实体model 换乘新的【plist中的model】

     //取缓存 look

 -(NSArray *)checkMember{

     //创建一个请求对象 填入要查询的表名-实体类

     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyOwnCoreData"];

     

     //    排序   -----------以身高进行升序排列yes   no表示降序

     NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];

     request.sortDescriptors = @[sort];

     

     NSError *error = nil;

     NSArray * emps = [self.context executeFetchRequest:request error:&error];

     if (emps.count > 0) {

         for (MyOwnCoreData *emp in emps) {

             NSLog(@"--read----%@---%lld",emp.name,emp.age);

         }

         return emps;

     }else{

         NSLog(@"没有缓存");

     }

     return @[];

 }


//     addMember 中

//     将 model 换成新的 即plist中的

//     将字段的赋值 根据需求赋值

     //add

 -(void)addMember:(MyOwnCoreData *)data{

     MyOwnCoreData *cat = [NSEntityDescription insertNewObjectForEntityForName:@"MyOwnCoreData" inManagedObjectContext:self.context];

     cat.name = data.name;

     cat.age = data.age;

     //下面 设置其他字段

     NSError *error = nil ;

     [self.context save:&error];

     

     if (error) {

         NSLog(@"-----insert-------%@",error);

     }else

     {

         NSLog(@"------insert sccess--------");

     }

 }


//     deleteMember 中

//     将 model 换成新的

//     将谓词中 查找的字段换成需要的

     //delete

 -(void)deleteMember:(MyOwnCoreData *)data{

     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyOwnCoreData"];

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",data.name];

     //下面可以写根据其他字段删除

     

     request.predicate = predicate ;

     NSError *error = nil;

     NSArray *objs = [self.context executeFetchRequest:request error:&error];//执行我们的请求

     //    2.删除

     for (MyOwnCoreData *entiy in objs) {

         [self.context deleteObject:entiy];

     }

     [self.context save:&error];

     if (error) {

         NSLog(@"%@",error);

     }else{

         NSLog(@"delete success");

     }

 }



//     updateWithOriginalData 中

//     将 Model 换成新的

//     将谓词 查找到的字段改成需求

//     将修改的值 赋值

     //updata

 -(void)updateWithOriginalData:(MyOwnCoreData *)originData ToCurrentData:(MyOwnCoreData *)currentData{

     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyOwnCoreData"];

     //需要将 name改成其他合适字段

     //根据字段查找需要修改的数据

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",originData.name];

     request.predicate = predicate ;

     NSArray *emps = [self.context executeFetchRequest:request error:nil];

     //改成新的数据

     if (emps.count) {

         for (MyOwnCoreData *entiy in emps) {

             entiy.name = currentData.name;

             entiy.age = currentData.age;

         }

     }

     NSError *error= nil;

     //    3.同步保存到数据库

     [self.context save:&error];

     if (error) {

         NSLog(@"update failed ---%@",error);

     }else{}

     NSLog(@"update success");

     

 }

     

     


//网络加载图片

- (void)ShowImageWithUrlStr: (NSString *)URLStr completion:(ResultDown)completion


#pragma mark - 新闻跑马灯两行

<TextInfoViewDelegate>

#import "XLsn0wTextCarousel.h"

#import "TextInfoView.h"

#import "DataSourceModel.h"


 -(void)setNewsArr:(NSArray *)newsArr{

     dataSourceArray_ = [NSMutableArray new];

     for (homeNewsListEntity *entity in newsArr) {

         //下面的 URLString 到时候点击需要传什么参数就传什么参数 一般是id

         DataSourceModel *model = [DataSourceModel dataSourceModelWithType:entity.newwRemark title:entity.newwDescribe URLString:entity.newwHtml tailTime:@"2017-02-14"];

         [dataSourceArray_ addObject:model];

     }

     XLsn0wTextCarousel *view = [[XLsn0wTextCarousel alloc] initWithFrame:CGRectMake(0, 0, newsView_.frame.size.width, newsView_.frame.size.height)];

     [newsView_ addSubview:view];

     view.dataSourceArray = dataSourceArray_;

     view.currentTextInfoView.xlsn0wDelegate = self;

     view.hiddenTextInfoView.xlsn0wDelegate = self;

     view.backgroundColor =[UIColor whiteColor];

 }


 - (void)handleTopEventWithURLString:(NSString *)URLString {

     NewsWebViewController *vc = [NewsWebViewController new];

     vc.newsURL =  URLString;

     [[KeepAppBox viewController:self].navigationController pushViewController:vc animated:YES];

 }

 

 - (void)handleBottomEventWithURLString:(NSString *)URLString {

     NewsWebViewController *vc = [NewsWebViewController new];

     vc.newsURL =  URLString;

     [[KeepAppBox viewController:self].navigationController pushViewController:vc animated:YES];

 }


#pragma mark - 将plist 文件转成 NSArray

 NSString *filePath = [[NSBundle mainBundle]pathForResource:@"BtnList.plist" ofType:nil];

 NSArray *contentArray = [NSArray arrayWithContentsOfFile:filePath];


#pragma mark - 旋转菜单

#import "FTT_Roundview.h"

     @property (nonatomic , strong) UIButton *button;

     @property (nonatomic , strong) FTT_Roundview *romate ;

     @property (nonatomic , strong) NSMutableArray *datasource ;


     FTT_Roundview *romate = [[FTT_Roundview alloc]initWithFrame:CGRectMake(0, 0, 400, 400)];

     romate.center = self.view.center;

     self.romate = romate;

     //将exe请求的数据 放在这里面【存实体,后面取出图片和文字】

     _datasource = [NSMutableArray new];

     [romate BtnType:(FTT_RoundviewTypeCustom) BtnWitch:100 adjustsFontSizesTowidth:YES msaksToBounds:YES conrenrRadius:50 image:imageArray TitileArray:titleArray titileColor:[UIColor purpleColor]];

     __weak ViewController *weakself = self;

     romate.back = ^(NSInteger num ,NSString *name ) {

         [weakself pushView:num name:name];

     };

     [self.view addSubview:romate];

     

     _button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

     _button.center = romate.center;

     _button.backgroundColor = [UIColor yellowColor];

     _button.layer.cornerRadius = 50;

     [_button addTarget:self action:@selector(showItems:) forControlEvents:UIControlEventTouchUpInside];

     [self.view addSubview:_button];

     

     - (void)showItems:(UIButton *)sender{

         [_romate show];

     }

     

     // 跳转界面

     - (void)pushView:(NSInteger)num name:(NSString *)name {

         FirstViewController *vc = [FirstViewController new];

         [self.navigationController pushViewController:vc animated:YES];

     }


#pragma mark - collectionView 拖拽

//参考collectionView拖拽Demo


#pragma amrk - 曲线和柱状图

//参考曲线和柱状图

 

#pragma mark - 加减count


 #import "ATChooseCountView.h"

 @property (nonatomic, strong) ATChooseCountView *chooseCountView;

     

 //可以控制 大小 设置width 可控制中间的宽度,height 可以控制高度,但是内容不发没有改变

 ATChooseCountView *chooseCountView = [[ATChooseCountView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];

 chooseCountView.center = CGPointMake(self.view.center.x, 200.0f);

 chooseCountView.countColor = [UIColor redColor];

 chooseCountView.canEdit = NO;

 [self.view addSubview:chooseCountView];

 [chooseCountView returnCount:^(NSInteger count) {

    NSLog(@"%ld",count);

}];



#pragma mark - 说说添加图片

//拉入库 说说添加图片

#import "MXPhotoView.h"


     //可以设置 位置 每行图片个数等

 self.edgesForExtendedLayout = UIRectEdgeNone;

 MXPhotoView *photoView = [[MXPhotoView alloc] initWithFrame:CGRectMake(0, 200, 414, 500)];

 photoView.photoViewDele = self;

 photoView.isNeedMovie = YES;

 photoView.showNum = 5;

 [self.view addSubview:photoView];

     

     

#pragma mark - 校验车牌号

/**

 * @brief 校验车牌号

 */

 + (BOOL)isValidateCarNo:(NSString *)carNo

{

    //    NSString *carRegex = @"^[A-Za-z]{1}[A-Za-z_0-9]{5}$";

    //    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];

    //    NSLog(@"carTest is %@",carTest);

    //    return [carTest evaluateWithObject:carNo];

    

    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{5}$";

    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", carRegex];

    NSLog(@"carTest is %@", carTest);

    return [carTest evaluateWithObject:carNo];

}


#pragma mark - 判断是否在时间段内

/**

 * @brief 判断当前时间是否在fromHour和toHour之间。如,fromHour=8,toHour=23时,即为判断当前时间是否在8:00-23:00之间

 */

 - (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour

{

    NSDate *date8 = [self getCustomDateWithHour:8];

    NSDate *date23 = [self getCustomDateWithHour:23];

    

    NSDate *currentDate = [NSDate date];

    

    if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending)

    {

        NSLog(@"该时间在 %d:00-%d:00 之间!", (int)fromHour, (int)toHour);

        return YES;

    }

    return NO;

}


#pragma mark - 给一个图片添加动画【可以在放在button点击事件中】

     [self imgAnimate:sender];

     

     - (void)imgAnimate:(UIButton*)btn{

         

         UIView *view=btn.subviews[0];

         

         [UIView animateWithDuration:0.1 animations:

          ^(void){

              

              view.transform = CGAffineTransformScale(CGAffineTransformIdentity,0.8, 0.8);

              

              

          } completion:^(BOOL finished){//do other thing

              [UIView animateWithDuration:0.2 animations:

               ^(void){

                   

                   view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.1, 1.1);

                   

               } completion:^(BOOL finished){//do other thing

                   [UIView animateWithDuration:0.1 animations:

                    ^(void){

                        

                        view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1,1);

                        

                        

                    } completion:^(BOOL finished){//do other thing

                    }];

               }];

          }];

     }


     

     

 //选择图片 <UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UITextViewDelegate>

 - (IBAction)PicSelectClick:(UIButton *)sender {

     UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:nil

                                                         delegate:self

                                                cancelButtonTitle:@"取消"

                                           destructiveButtonTitle:nil

                                                otherButtonTitles:@"拍照",@"从手机相册取", nil];

     

     action.actionSheetStyle = UIActionSheetStyleDefault;

     [action showInView:self.view];

 }

 

 -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

    switch (buttonIndex)

    {

        case 0:

        {

            [self takeCameral];

        }

            break;

        case 1:

        {

            [self searchLibrary];

        }

            break;

        default:

            break;

    }

}

 

#pragma mark - UIActionSheetDelegate

 - (void)takeCameral

{

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

    {

        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        imagePicker.delegate = self;

        [imagePicker setAllowsEditing:NO];

        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        [self presentViewController:imagePicker animated:YES completion:nil];

    }else{

        [SVProgressHUD showInfoWithStatus:@"相机不可用"];

    }

}

 

 - (void)searchLibrary

{

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])

    {

        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        imagePicker.delegate = self;

        [imagePicker setAllowsEditing:NO];

        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

        [self presentViewController:imagePicker animated:YES completion:nil];

    }

}

 

#pragma mark - UIImagePickerControllerDelegate

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    [picker dismissViewControllerAnimated:YES completion:^() {

        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

        portraitImg = [self imageByScalingToMaxSize:portraitImg];

        [addPhotoBtn_ setImage:cardImageFirst_ forState:UIControlStateNormal];

    }];

}

 

#pragma mark - Image Scale Utility

 

 - (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage

{

    if (sourceImage.size.width < SCREEN_WIDTH * 2) return sourceImage;

    CGFloat btWidth = 0.0f;

    CGFloat btHeight = 0.0f;

    if (sourceImage.size.width > sourceImage.size.height) {

        btHeight = SCREEN_WIDTH * 2;

        btWidth = sourceImage.size.width * (SCREEN_WIDTH * 2 / sourceImage.size.height);

    } else {

        btWidth = SCREEN_WIDTH * 2;

        btHeight = sourceImage.size.height * (SCREEN_WIDTH * 2 / sourceImage.size.width);

    }

    CGSize targetSize = CGSizeMake(btWidth, btHeight);

    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];

}

 

 - (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize

{

    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;

    CGFloat width = imageSize.width;

    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;

    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;

    CGFloat scaledWidth = targetWidth;

    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)

    {

        CGFloat widthFactor = targetWidth / width;

        CGFloat heightFactor = targetHeight / height;

        

        if (widthFactor > heightFactor)

            scaleFactor = widthFactor; // scale to fit height

        else

            scaleFactor = heightFactor; // scale to fit width

        scaledWidth  = width * scaleFactor;

        scaledHeight = height * scaleFactor;

        

        // center the image

        if (widthFactor > heightFactor)

        {

            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

        }

        else

            if (widthFactor < heightFactor)

            {

                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;

            }

    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;

    thumbnailRect.origin = thumbnailPoint;

    thumbnailRect.size.width  = scaledWidth;

    thumbnailRect.size.height = scaledHeight;

    

    [sourceImage drawInRect:thumbnailRect];

    

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil) NSLog(@"could not scale image");

    

    //pop the context to get back to the default

    UIGraphicsEndImageContext();

    return newImage;

}


#pragma mark - pickerview

#import "MMPickerView.h"


 @property (nonatomic, strong) NSArray *stringsArray;

 @property (nonatomic, strong) NSArray *numbersArray;

 @property (nonatomic, strong) NSString * selectedString;


 _stringsArray = @[@"Easy to use", @"Time-saver", @"Customizable", @"Only a few lines of code", @"Works with custom fonts"];

 _selectedString = [_stringsArray objectAtIndex:0];


 - (IBAction)clickk:(id)sender {

     [MMPickerView showPickerViewInView:self.view

                            withStrings:_stringsArray

                            withOptions:@{MMbackgroundColor: [UIColor whiteColor],

                                          MMtextColor: [UIColor blackColor],

                                          MMtoolbarColor: [UIColor whiteColor],

                                          MMbuttonColor: [UIColor blueColor],

                                          MMfont: [UIFont systemFontOfSize:18],

                                          MMvalueY: @3,

                                          MMselectedObject:_selectedString,

                                          MMtextAlignment:@1}

                             completion:^(NSString *selectedString) {

                                 

                                 //                                _label.text = selectedString;

                                 

                                 NSLog(@"%@",selectedString);

                                 

                                 _selectedString = selectedString;

                             }];

 }

     

#pragma mark - 字典转字符串

 - (NSString*)dictionaryToJson:(NSDictionary *)dic

{

    NSError *parseError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

     

#pragma mark - 字典转nsdata

     postBody =  [NSStringFromQueryParameters(info) dataUsingEncoding:NSUTF8StringEncoding];

     

     static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)

     {

         NSMutableArray* parts = [NSMutableArray array];

         [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {

             NSString *part = [NSString stringWithFormat: @"%@=%@",

                               [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],

                               [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]

                               ];

             [parts addObject:part];

         }];

         return [parts componentsJoinedByString: @"&"];

     }

     

#pragma mark - 字符串转字典

     SBJsonParser *parser = [[SBJsonParser alloc] init];

     NSDictionary *parserDict = [parser objectWithString:aStr];

     //字典转字符串

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

     return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

     

#pragma mark - wkwebview 访问http没反应!

    //将url转换一下 【_htmlUrl】 将网址转换成utf8码即可

     _htmlUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)_htmlUrl, nil, nil, kCFStringEncodingUTF8));

     _htmlUrl = [_htmlUrl stringByAddingPercentEscapesUsingEncoding:(kCFStringEncodingUTF8)];

 #pragma mark - 打电话

 

 if (APPTechnologyHotLineEntity_.APPTeachnologHotline.length == 0) {

     [SVProgressHUD showInfoWithStatus:@"号码不存在"];

     return;

 }

 [self phoneTo:APPTechnologyHotLineEntity_.APPTeachnologHotline];

 

 -(void)phoneTo:(NSString *)phone{

     

     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"确认拨打电话 %@",phone] preferredStyle:UIAlertControllerStyleAlert];

     UIAlertAction *actionCannel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

         return ;

     }];

     UIAlertAction *actionSure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

         

         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];

         //        return ;

     }];

     [alertController addAction:actionSure];

     [alertController addAction:actionCannel];

     [self presentViewController:alertController animated:YES completion:nil];

 }

     

#pragma mark - 查看大照片

 PhotoLookBigPicViewController *toCtrol = [[PhotoLookBigPicViewController alloc] init];

 NSArray *imageDisplayArr = [NSArray arrayWithArray:AchieveQueryDetailEntity_.imageDisplay];

 NSMutableArray *picArr = [NSMutableArray new];

 for (NSDictionary *dict in imageDisplayArr) {

     [picArr addObject:[dict objectForKey:@"picPath"]];

     toCtrol.picMapList = (NSArray *)imgArr_[0];

     toCtrol.currentPage = 1;

     toCtrol.currentPage = 1;

     [self.navigationController pushViewController:toCtrol animated:YES];

         

     -(void)viewWillAppear:(BOOL)animated{

         [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"组-8"] forBarMetrics:UIBarMetricsDefault];

     }


     

#pragma mark - 单例

     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isFirst"];

     BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:@"isFirst"];

     

#pragma mark - cell随着 里面的文字多少 变换高度,达到换行效果

     //将需要进行换行的label进行约束上下左右,设置行数为0

     //计算label的宽度 屏幕宽度减去左右到屏幕的距离

     //然后在heightForRowAtIndexPath 里面使用动态计算高度方法

     //计算出字应该占有的高度或宽度,计算出来看看上方控件有几个一个控件加一个锚点高度0.5 最后+0.5

     //在请求待数据的时候 reloaddata。

     //* 如果再遇到这类问题,可是尝试使用老方法,计算文字的总高度直接赋值给label 在heightForRow中计算文字高度 加上多出来的高度即可。

#pragma mark - 执行某个方法 延迟和带参数

     [self performSelector:@selector(refreshFromLast) withObject:nil afterDelay:0.2f];

     

#pragma mark - SVProgressHUD设置

     [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];//设置HUD的Style

     [SVProgressHUD setForegroundColor:[UIColor redColor]];//设置HUD和文本的颜色

     [SVProgressHUD setBackgroundColor:[UIColor magentaColor]];//设置HUD的背景颜色

     /**

      *  设置HUD背景图层的样式

      *

      *  SVProgressHUDMaskTypeNone:默认图层样式,当HUD显示的时候,允许用户交互。

      *

      *  SVProgressHUDMaskTypeClear:当HUD显示的时候,不允许用户交互。

      *

      *  SVProgressHUDMaskTypeBlack:当HUD显示的时候,不允许用户交互,且显示黑色背景图层。

      *

      *  SVProgressHUDMaskTypeGradient:当HUD显示的时候,不允许用户交互,且显示渐变的背景图层。

      *

      *  SVProgressHUDMaskTypeCustom:当HUD显示的时候,不允许用户交互,且显示背景图层自定义的颜色。

      */

     [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom]; //设置HUD背景图层的样式

     [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];

     //取消显示HUD

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

         [SVProgressHUD dismiss];

     });

     button.userInteractionEnabled = NO;

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

         button.userInteractionEnabled = YES;

     });

     

#pragma mark - self.title

     self.navigationItem.title = @"首页";

     self.tabBarItem.title = @"";

     self.title = @"";

#pragma mark - arc

     CGFloat a = 0;

     a = arc4random()%2 +1;

     if (a == 1) {

         

     }else{

         

     }

     

#pragma mark - ChosePhoto 选择照片

#warning 如果需要排列多排。只要将高度设置两倍item高度 并设置为上下滑动即可

     

     -(void)chineseBoxPhotosDisplay{

         if (BB_) {

             [BB_ removeFromSuperview];

             BB_ = nil;

         }

         if (!BB_) {

             BBArr_ = [NSMutableArray new];

             for (shopPhotoEntity *entity in chineseBoxPhotosArr_) {

                 [BBArr_ addObject:entity.picPath];

             }

             BB_ = [[ChosePhoto alloc] initWithFrame:CGRectMake(0, 0, actualV.frame.size.width, actualV.frame.size.height) AndItemSize:CGSizeMake(80, 60) AndPhotos:BBArr_ Target:self AndBlock:^(NSArray *imageArr) {

                 

                 id obj = imageArr[0];

                 if ([obj isKindOfClass:[UIImage class]]) {

                     //进行网络请求上传图片

                     BBArr_ = [NSMutableArray arrayWithArray:imageArr];

                     [self chineseBoxUpLoad];

                 }else if ([obj isKindOfClass:[NSString class]]){

                     //如果是传的string值 取出字段进行判断 弹出PopView 提示不可编辑正在审核

                     NSString *panduan = obj;

                     if ([panduan isEqualToString:@"PopView"]) {

                         PopView *popV = [[PopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 40, SCREEN_WIDTH/3*2) title:@"友情提示" message:@"您已经提交该信息且正在系统审核,请耐心等待..." isNeedCancel:NO isSureBlock:^(BOOL sureBlock) {

                             //                [self.navigationController popViewControllerAnimated:YES];

                         }];

                         [popV setSecTitleBackColor:UIColorFromRGB(0x47B0EB)];

                         [popV setSecSureColor:UIColorFromRGB(0x47B0EB)];

                         [popV setSecMessageColor:UIColorFromRGB(0x666666)];

                         [self.view addSubview:popV];

                     }

                 }else if ([obj isKindOfClass:[NSDictionary class]]){

                     //self.imageBack(@[@{@"deleteIndex":deleteIndex}]);

                     NSDictionary *dict = obj;

                     //当有删除需求

                     NSString *deleteIndex = [dict objectForKey:@"deleteIndex"];

                     if (deleteIndex.length > 0) {

                         NSInteger index = [deleteIndex integerValue];

                         [chineseBoxPhotosArr_ removeObjectAtIndex:index];

                     }

                     //如果是有最大限制 当超出限制时候 传出提示

                     NSString *maxCount = [dict objectForKey:@"maxCount"];

                     if (maxCount.length > 0) {

                         [SVProgressHUD showInfoWithStatus:@"已超出最大限制张数"];

                     }

                     

                 }

             }];

             //    cc.ViewBackColor = [UIColor blueColor];

             //    cc.CollectionViewBackColor = [UIColor lightGrayColor];

             //        BB_.MaxCount = 4;

             [actualV addSubview:BB_];

         }

         BB_.isCanTouchPhoto = NO;

     }

     

#pragma mark - 中国盒上传

     - (void)chineseBoxUpLoad

     {

         [SVProgressHUD show];

         [self setButtonUnable];

         NSMutableDictionary *sendDic = [[NSMutableDictionary alloc] initWithCapacity:2];

         

         for (int i = 0; i < BBArr_.count; i++) {

             //上传高清图片

             UIImage *image;

             //        if ([[AAArr_ objectAtIndex:i] isKindOfClass:[SGPhoto class]])

             //        {

             //            SGPhoto *temp = [AAArr_ objectAtIndex:i];

             //            image = temp.fullResolutionImage;

             //        }

             //        else

             //        {

             image = [BBArr_ objectAtIndex:i];

             //        }

             NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:7];

             [params setObject:[NSString stringWithFormat:@"%@.png",@(i)] forKey:@"imageFileName"];

             

             NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

             [storeManageManager execute:@selector(StorePhotoEditManager) target:self callback:@selector(chineseBoxUpLoadCallBack:) args:sendDic, imageData,nil];

             

         }

         

     }

     

     - (void)chineseBoxUpLoadCallBack:(id)data

     {

         if (data)

         {

             if ([data objectForKey:kWrongDlog]) {

                 [SVProgressHUD showErrorWithStatus:[data objectForKey:kWrongDlog]];

                 

             }else{

                 [SVProgressHUD dismiss];

                 shopPhotoEntity_ = [data objectForKey:@"picEntity"];

                 [chineseBoxPhotosArr_ addObject:shopPhotoEntity_];

                 [self chineseBoxPhotosDisplay];

                 [self setButtonAble];

             }

             

             

         }

         else

         {

             [SVProgressHUD showErrorWithStatus:kDefaultMsg];

         }

         //下拉刷新变量设置成可刷新状态

         //    needReloading_ = NO;

         //    [self doneLoadingTableViewData];

     }

     

#pragma mark - 点击跳转相册

     SGPhoto *temp = [[SGPhoto alloc] init];

     temp.identifier = @"";

     temp.thumbnail = [NFUserEntity shareInstance].mineHeadViewImage;

     temp.fullResolutionImage = [NFUserEntity shareInstance].mineHeadViewImage;

     HDPictureShowViewController *showImageViewCtrol = [[HDPictureShowViewController alloc] init];

     showImageViewCtrol.imageUrlList = @[temp];

     showImageViewCtrol.mainImageIndex = 0;

     showImageViewCtrol.isLuoYang = YES;

     showImageViewCtrol.isNeedNavigation = NO;

     [self.navigationController pushViewController:showImageViewCtrol animated:YES

      ];

     

#pragma mark - 手势放大缩小图片

     // 缩放手势

     UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)];

     [imageView addGestureRecognizer:pinchGestureRecognizer];

     

     // 移动手势

     UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];

     [imageView addGestureRecognizer:panGestureRecognizer];

     

     //    UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotateView:)];

     //    [imageView addGestureRecognizer:rotationGestureRecognizer];

     

     // 处理旋转手势

     //+ (void) rotateView:(UIRotationGestureRecognizer *)rotationGestureRecognizer

     //{

     //    UIView *view = rotationGestureRecognizer.view;

     //    if (rotationGestureRecognizer.state == UIGestureRecognizerStateBegan || rotationGestureRecognizer.state == UIGestureRecognizerStateChanged) {

     //        view.transform = CGAffineTransformRotate(view.transform, rotationGestureRecognizer.rotation);

     //        [rotationGestureRecognizer setRotation:0];

     //    }

     //}

     

     // 处理缩放手势

     + (void) pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer

     {

         UIView *view = pinchGestureRecognizer.view;

         UIImageView *imageView=(UIImageView*)[pinchGestureRecognizer.view viewWithTag:1];

         if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged) {

             view.transform = CGAffineTransformScale(view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);

             pinchGestureRecognizer.scale = 1;

         }

         else if (pinchGestureRecognizer.state == UIGestureRecognizerStateEnded) {

             NSLog(@"");

             //

             NSLog(@"%f\n%f",imageView.frame.size.width,orginFrame.size.width);

             //控制大小在一倍到三倍之间

             if (imageView.frame.size.width < orginFrame.size.width) {

                 [UIView animateWithDuration:0.3 animations:^{

                     /**

                      *  固定一倍

                      */

                     imageView.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0);

                 } completion:^(BOOL finished) {

                 }];

             }

             if (imageView.frame.size.width > orginFrame.size.width * 3) {

                 [UIView animateWithDuration:0.3 animations:^{

                     /**

                      *  固定三倍

                      */

                     imageView.transform = CGAffineTransformMake(3, 0, 0, 3, 0, 0);

                 } completion:^(BOOL finished) {

                 }];

             }

             //控制左右不越界

             if (imageView.frame.origin.x > 0) {

                 CGRect rect = imageView.frame;

                 rect.origin.x = 0;

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }else if (CGRectGetMaxX(imageView.frame) < SCREEN_WIDTH){

                 CGRect rect = imageView.frame;

                 rect.origin.x += (SCREEN_WIDTH - CGRectGetMaxX(imageView.frame));

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }

             //控制上下不越界

             if (imageView.frame.origin.y > 0 && CGRectGetMaxY(imageView.frame) > SCREEN_HEIGHT) {

                 CGRect rect = imageView.frame;

                 //            if (CGRectGetMidY(imageView.frame) > SCREEN_HEIGHT/2) {

                 //                rect.origin.y -=  ((CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT));

                 //            }else{

                 //                rect.origin.y = 0;

                 //            }

                 

                 if ((CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT) < CGRectGetMinY(imageView.frame)) {

                     rect.origin.y -=  ((CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT));

                 }else{

                     rect.origin.y = 0;

                 }

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }else if (imageView.frame.origin.y < 0 && CGRectGetMaxY(imageView.frame) < SCREEN_HEIGHT){

                 CGRect rect = imageView.frame;

                 if ((SCREEN_HEIGHT - CGRectGetMaxY(imageView.frame))-(imageView.frame.size.height - CGRectGetMaxY(imageView.frame)) > 0) {

                     rect.origin.y = 0;

                 }else{

                     rect.origin.y -=  ((CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT));

                 }

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }

         }

     }

     

     // 处理拖拉手势

     + (void) panView:(UIPanGestureRecognizer *)panGestureRecognizer

     {

         UIView *view = panGestureRecognizer.view;

         UIImageView *imageView=(UIImageView*)[panGestureRecognizer.view viewWithTag:1];

         if (panGestureRecognizer.state == UIGestureRecognizerStateBegan || panGestureRecognizer.state == UIGestureRecognizerStateChanged) {

             if (imageView.frame.origin.x == orginFrame.origin.x && imageView.frame.origin.y == orginFrame.origin.y) {

                 //当没有放大缩小 不能拖动

                 return;

             }

             CGPoint translation = [panGestureRecognizer translationInView:view.superview];

             [view setCenter:(CGPoint){view.center.x + translation.x, view.center.y + translation.y}];

             [panGestureRecognizer setTranslation:CGPointZero inView:view.superview];

         }else if (panGestureRecognizer.state == UIGestureRecognizerStateEnded) {

             NSLog(@"");

             //控制左右不越界

             if (imageView.frame.origin.x > 0) {

                 CGRect rect = imageView.frame;

                 rect.origin.x = 0;

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }else if (CGRectGetMaxX(imageView.frame) < SCREEN_WIDTH){

                 CGRect rect = imageView.frame;

                 rect.origin.x += (SCREEN_WIDTH - CGRectGetMaxX(imageView.frame));

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }

             //控制上下不越界

             if (imageView.frame.origin.y > 0 && CGRectGetMaxY(imageView.frame) > SCREEN_HEIGHT) {

                 //超下边界

                 CGRect rect = imageView.frame;

                 //            if (CGRectGetMidY(imageView.frame) > SCREEN_HEIGHT/2) {

                 //                rect.origin.y -=  ((CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT));

                 //            }else{

                 //                rect.origin.y = 0;

                 //            }

                 if (imageView.frame.size.height > SCREEN_HEIGHT) {

                     rect.origin.y = 0;

                 }else{

                     rect.origin.y = (CGRectGetMinY(imageView.frame) - (CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT))/2;

                 }

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }else if (imageView.frame.origin.y < 0 && CGRectGetMaxY(imageView.frame) < SCREEN_HEIGHT){

                 //超上边界

                 CGRect rect = imageView.frame;

                 if ((SCREEN_HEIGHT - CGRectGetMaxY(imageView.frame))-(imageView.frame.size.height - CGRectGetMaxY(imageView.frame)) > 0) {

                     //图片偏下

                     //                rect.origin.y = 0;

                     //                CGFloat Y = (SCREEN_HEIGHT - CGRectGetMaxY(imageView.frame))/2;

                     //                rect.origin.y = Y;

                     

                     if (imageView.frame.size.height > SCREEN_HEIGHT) {

                         rect.origin.y = (SCREEN_HEIGHT - CGRectGetMaxY(imageView.frame));

                     }else{

                         rect.origin.y = (SCREEN_HEIGHT - CGRectGetMaxY(imageView.frame) - (imageView.frame.size.height - CGRectGetMaxY(imageView.frame)))/2;

                     }

                     

                 }else{

                     //图片偏上

                     //                rect.origin.y -=  ((CGRectGetMaxY(imageView.frame) - SCREEN_HEIGHT));

                     //                CGFloat Y = (CGRectGetMaxY(imageView.frame) - CGRectGetMinY(imageView.frame))/2;

                     CGFloat Y = SCREEN_HEIGHT - CGRectGetMaxY(imageView.frame);

                     rect.origin.y += Y;

                     

                 }

                 [UIView animateWithDuration:0.3 animations:^{

                     imageView.frame = rect;

                 } completion:^(BOOL finished) {

                 }];

             }

         }

     }

     


     

     

     

     

#pragma mark - 点击确定时候 判断 是否编辑过照片 是否上传空照片

     BOOL isChangePhoto;

     if (isChangePhoto) {

         //当编辑后 并且移除了所有照片后

         if (shopAllroundViewArr_.count == 0 &&chineseBoxPhotosArr_.count == 0 &&materialDisplayArr_.count == 0 &&photoTypeDisplayArr_.count == 0 &&shopPractisePhotosArr_.count == 0) {

             PopView *popV = [[PopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 30, SCREEN_WIDTH /3*2) title:@"温馨提示" message:@"您是否确定移除所有图片么?" isNeedCancel:YES isSureBlock:^(BOOL sureBlock) {

                 if (sureBlock) {

                     [self sureEditPhotoManager];

                 }

             }];

             [popV setSecTitleBackColor:UIColorFromRGB(0x47B0EB)];

             [popV setSecSureColor:UIColorFromRGB(0x47B0EB)];

             [popV setSecMessageColor:[UIColor darkGrayColor]];

             storePhotoTableV.scrollEnabled = NO;

             [self.view addSubview:popV];

             

         }

         else{

             //当编辑地不为空时

             [self sureEditPhotoManager];

         }

     }else{

         //当没有进行编辑时候

         PopView *popV = [[PopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 30, SCREEN_WIDTH /3*2) title:@"温馨提示" message:@"您伟修改任何图片,无需提交!" isNeedCancel:NO isSureBlock:^(BOOL sureBlock) {

         }];

         [popV setSecTitleBackColor:UIColorFromRGB(0x47B0EB)];

         [popV setSecSureColor:UIColorFromRGB(0x47B0EB)];

         [popV setSecMessageColor:[UIColor darkGrayColor]];

         storePhotoTableV.scrollEnabled = NO;

         [self.view addSubview:popV];

     }



#pragma mark -PickerViewChose 多个compont

     //初始化 在initui中

     pickV = [[PickerViewChose alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 250, SCREEN_WIDTH, 250) FirstCompontArr:@[@"1",@"2",@"3"] SecondCompont:@[@"1",@"2",@"3"] ThirdCompont:@[@"1",@"2",@"3"] forthCompont:@[] rowHeight:50 ReturnEveryRowBlock:^(BOOL isSure,NSInteger firstRow, NSInteger secondRow, NSInteger thirdRow, NSInteger forthRow) {

         [backV_ removeFromSuperview];

         

     }];

     

     //将pickerview放到界面上去 backV_ secBackV 在点击事件中

     backV_ = [[UIView alloc] initWithFrame:self.view.bounds];

     backV_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

     backV_.backgroundColor = [UIColor clearColor];

     UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];

     [win addSubview:backV_];

     

     secBackV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

     secBackV.backgroundColor = [UIColor blackColor];

     secBackV.alpha = 0.5;

     [backV_ addSubview:secBackV];

     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackgroundClickk)];

     [secBackV addGestureRecognizer:tap];

     [backV_ addSubview:pickV];

     -(void)tapBackgroundClickk{

         [UIView animateWithDuration:0.2 animations:^{

             //将某个tableview 经过动画缩小到右上角一点

             pickV.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 0.1);

         } completion:^(BOOL finished) {

             [backV_ removeFromSuperview];

         }];

     }

     

     

     // SVPHUDProgress延迟2秒后消失

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

         [SVProgressHUD dismiss];

     });

     

#pragma mark -PickerViewChose 单个compont

     #import "PickerViewChose.h"

     PickerViewChose *pickV;

     //最底下clear 背景

     UIView *backV_;

     //第二层 半透明背景

     UIView *secBackV;

     NSInteger firstRow_;

     NSInteger secondRow_;

     NSInteger thirdRow_;


     - (IBAction)problemTypeChoseClick:(id)sender {

         //将pickerview放到界面上去 backV_ secBackV

         backV_ = [[UIView alloc] initWithFrame:self.view.bounds];

         backV_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

         backV_.backgroundColor = [UIColor clearColor];

         UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];

         [win addSubview:backV_];

         

         secBackV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

         secBackV.backgroundColor = [UIColor blackColor];

         secBackV.alpha = 0.5;

         [backV_ addSubview:secBackV];

         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackgroundClickk)];

         [secBackV addGestureRecognizer:tap];

         

         [backV_ addSubview:pickV];

     }

     

     -(void)tapBackgroundClickk{

         [UIView animateWithDuration:0.2 animations:^{

             //将某个tableview 经过动画缩小到一点

             pickV.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 0.1);

         } completion:^(BOOL finished) {

             pickV.frame = CGRectMake(0, SCREEN_HEIGHT - 250, SCREEN_WIDTH, 250);

             [backV_ removeFromSuperview];

         }];

     }

     

     -(void)createPickerView{

         NSArray *arr = @[@"分类一",@"分类二",@"分类三"];

         pickV = [[PickerViewChose alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 250, SCREEN_WIDTH, 250) FirstCompontArr:arr SecondCompont:@[] ThirdCompont:@[] forthCompont:@[] rowHeight:50 ReturnEveryRowBlock:^(BOOL isSure,NSInteger firstRow, NSInteger secondRow, NSInteger thirdRow, NSInteger forthRow) {

             [UIView animateWithDuration:0.2 animations:^{

                 //将某个tableview 经过动画缩小到一点

                 pickV.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 0.1);

             } completion:^(BOOL finished) {

                 pickV.frame = CGRectMake(0, SCREEN_HEIGHT - 250, SCREEN_WIDTH, 250);

                 [backV_ removeFromSuperview];

             }];

             //日后exe

             if (isSure) {

                 firstRow_ = firstRow;

                 if (firstRow_ == 0) {

                     [problemTypeBtn setTitle:@"分类一" forState:(UIControlStateNormal)];

                 }else if (firstRow_ == 1){

                     [problemTypeBtn setTitle:@"分类二" forState:(UIControlStateNormal)];

                 }else if (firstRow_ == 1){

                     [problemTypeBtn setTitle:@"分类三" forState:(UIControlStateNormal)];

                 }

             }

         }];

     }

     



#pragma mark - 应该返回{"list":[{"text":" DIY","code":" DIY"},{"text":" MNC","code":" MNC"},@{}]}

     可是返回了 {"list":[{"text":" DIY","code":" DIY"},{"text":" MNC","code":" MNC"},null]}

     //应该返回字典或数组 当返回 ,null, 的时候 需要移除

     //增加数据获取的健壮性

     bodyDic = [self changeType:bodyDic];

     

#pragma mark - 自定义边框线

     [_borderView1 setBorderColor:[UIColor redColor]];

     [_borderView2 setBorderType:ZDBorderTypeLeft|ZDBorderTypeRight];

     

     //自适应高度

     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};

     CGFloat height = [detailEntity_.storeName boundingRectWithSize:CGSizeMake(JOESIZE.width - 100, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;

     shopNameHeightContant.constant = height+ 0.1;

     

     //heightForRowAtIndexPath

     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};

     CGFloat height = [detailEntity_.storeName boundingRectWithSize:CGSizeMake(JOESIZE.width - 100, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;

     return 300 + (height - 20);

     

#pragmam mark - 密文显示

     passWordTextF_.secureTextEntry = YES;

     

#pragma mark - 画周围阴影

     UIBezierPath *path = [UIBezierPath bezierPath];

     

     [path moveToPoint:CGPointMake(-5, -5)];

     CGFloat paintingWidth = cell.frame.size.width;

     CGFloat paintingHeight = cell.frame.size.height;

     //添加直线

     [path addLineToPoint:CGPointMake(paintingWidth /2, -15)];

     [path addLineToPoint:CGPointMake(paintingWidth +5, -5)];

     [path addLineToPoint:CGPointMake(paintingWidth +15, paintingHeight /2)];

     [path addLineToPoint:CGPointMake(paintingWidth +5, paintingHeight +5)];

     [path addLineToPoint:CGPointMake(paintingWidth /2, paintingHeight +15)];

     [path addLineToPoint:CGPointMake(-5, paintingHeight +5)];

     [path addLineToPoint:CGPointMake(-15, paintingHeight /2)];

     [path addLineToPoint:CGPointMake(-5, -5)];

     //设置阴影路径

     cell.layer.shadowPath = path.CGPath;

     

#pragma mark - 设置cell阴影

     cell.layer.masksToBounds = NO;

     cell.layer.contentsScale = [UIScreen mainScreen].scale;

     cell.layer.shadowOpacity = 0.75f;

     cell.layer.shadowRadius = 5.0f;

     //shadowOffset属性控制着阴影的方向和距离。它是一个CGSize的值,宽度控制这阴影横向的位移,高度控制着纵向的位移。shadowOffset的默认值是 {0, -3},意即阴影相对于Y轴有3个点的向上位移

     cell.layer.shadowOffset = CGSizeMake(0,0);

     cell.layer.shadowPath = [UIBezierPath bezierPathWithRect:cell.bounds].CGPath;

     //设置缓存

     cell.layer.shouldRasterize = YES;

     //设置抗锯齿边缘

     cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

     

     

#pragma mark - 设置按钮阴影

     newChatButton.layer.shadowOffset =  CGSizeMake(1, 1);

     newChatButton.layer.shadowOpacity = 0.8;

     newChatButton.layer.shadowColor =  [UIColor blackColor].CGColor;

     

#pragma mark - 解析字符串

     entity.applyTime = [self NSStringWithKey:@"applyTime" fromDict:entityDic MethodName:@"ExamineHistoryListManagerParser:" parameterString:@"applyTime"];


#pragma mark - 加载标签 html

     NSString *str = @"<font color=\"#6c6c6c\">满20减5 满40减15,还剩<font color=\"#ff9147\">113天";

     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 50, 300, 50)];

     NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];

     label.attributedText = attrStr;

     //如果想要改变文字的字体,请在设置attributedText之后设置

     label.font = [UIFont systemFontOfSize:20];

     [self.view addSubview:label];

     

#pragma mark - 加载图片前先取缓存

     #import "UIImageView+HCDWebCache.h"

     [cell.imagee downImageWithString:arr[a] placeHolder:nil complete:^(UIImage *image) {

         //判断是否有图片,因为从磁盘里面获取的图片 第一次显示不出来 需要手动设置

         if (!cell.imagee.image) {

             cell.imagee.image = image;

         }

     }];

     

#pragma mark - 断点调试命令行

     -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

         //此处打断点

     }

     //打印视图的子视图个数

     p [[[self view] subviews] count]

 error: no known method '-count'; cast the message send to the method's return type

     p (int)[[[self view] subviews] count]

     

#pragma amrk - 当爆红崩溃全局断点找不到时 查看崩溃内容中可疑的内存

     //类似这个吧  可以打印出这次问题的方法

     3   LLEB                                0x0000000104b595ba -[ViewController viewDidLoad] + 138

     //或

 Address: LLEB[0x0000000100001696] (LLEB.__TEXT.__text + 438)

 Summary: LLEB`-[ViewController touchesBegan:withEvent:] + 150 at ViewController.m:40

     

     image lookup --address 0x00000001043ca533

     

#pragma mark - 移除子视图

     //移除所有子视图 已完成 未完成 延期 转授等图标 joe

     [calendarSectionHeadV.headView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

     

#pragma mark - 取实体

     [cell setCellWithInfoArr:infoArr_ andIndexPath:seletIndex_];

     

#pragma mark - 查看图片带手势

#import "HDPictureShowViewController.h"

     HDPictureShowViewController *showImageViewCtrol = [[HDPictureShowViewController alloc] init];

     showImageViewCtrol.imageUrlList = @[@"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=170651201,4118355521&fm=170&s=6BE28B47CE1231DC4B6408B20300E083&w=576&h=508&img.JPEG",@"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=170651201,4118355521&fm=170&s=6BE28B47CE1231DC4B6408B20300E083&w=576&h=508&img.JPEG"];

     showImageViewCtrol.mainImageIndex = 0;

     showImageViewCtrol.isLuoYang = YES;

     [self.navigationController pushViewController:showImageViewCtrol animated:YES

      ];

     //    [[self viewController].navigationController pushViewController:showImageViewCtrol animated:YES];

#pragma mark - 跳转需要获得父类viewctroller

     //- (UIViewController *)viewController

     //{

     //    for (UIView *next = [self superview]; next; next = next.superview)

     //    {

     //        UIResponder *nextResponder = [next nextResponder];

     //        if ([nextResponder isKindOfClass:[UIViewController class]])

     //        {

     //            return (UIViewController *)nextResponder;

     //        }

     //    }

     //    return nil;

     //}

     

#pragma mark - cell辅助视图

     if (indexPath == selectedIndePath) {

         UIImageView * checkImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 14)];

         if (!checkImageView.image)

         {

             checkImageView.image = [UIImage imageNamed:@"Sh_lvduihao"];

         }

         cell.accessoryView = checkImageView;

     }

     

#pragma mark - 取float后面两位小数

     CGFloat distanceValue = (CGFloat)((int)([self.stepTotalDistanceLabel.text floatValue]*100))/100;

     

#pragma mark - 苹果沙盒

     查看方法:

     方法1、可以设置显示隐藏文件,然后在Finder下直接打开。设置查看隐藏文件的方法如下:打开终端,输入命名

     (1)显示Mac隐藏文件的命令:defaults write com.apple.finder AppleShowAllFiles -bool true

     (2)隐藏Mac隐藏文件的命令:defaults write com.apple.finder AppleShowAllFiles -bool false

     (3)输完单击Enter键,退出终端,重新启动Finder就可以了 重启Finder:鼠标单击窗口左上角的苹果标志-->强制退出-->Finder-->

     现在能看到资源库文件夹了。

     打开资源库后找到/Application Support/iPhone Simulator/文件夹。这里面就是模拟器的各个程序的沙盒目录了。

     方法2、这种方法更方便,在Finder上点->前往->前往文件夹,输入/Users/username/Library/Application Support/iPhone Simulator/  前往。

     username这里写用户名。

     

#pragma mark - url转string

     NSString *urlStr = toURL.absoluteString;

     [self disposeSound:urlStr];

     

#pragma mark - 是否为汉字

     - (BOOL)isChinese:(NSString *)string

     {

         NSString *match = @"(^[\u4e00-\u9fa5]+$)";

         NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];

         return [predicate evaluateWithObject:string];

     }

     

#pragma mark - 开网

     <key>NSAppTransportSecurity</key>

     <dict>

     <key>NSAllowsArbitraryLoads</key>

     <true/>

     </dict>

     

     

#pragma mark - prefix header

     $(SRCROOT)/nationalFitness/BaseClasses/PublicDefine.h

     

     

#pragma mark - coredata 使用

     __weak typeof(self)weakSelf=self;

     __strong typeof(weakSelf)strongSelf=weakSelf;

     @property (nonatomic,strong)AppDelegate *appdelegate;

     

     //取

     NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"ContantListModel"];

     NSError *error = nil;

     NSArray *groupArr = [self.appdelegate.managedObjectContext executeFetchRequest:request error:&error];

     

     //存

     NSEntityDescription *description = [NSEntityDescription entityForName:@"ContantListModel" inManagedObjectContext:strongSelf.appdelegate.managedObjectContext];

     ContantListModel *contantModel = [[ContantListModel alloc]initWithEntity:description insertIntoManagedObjectContext:strongSelf.appdelegate.managedObjectContext];

     contantModel.name = userArray[i];

     contantModel.chatId = userArray[i];

     // 保存数据

     [strongSelf.appdelegate saveContext];

     

     //改

     Shoes *shoes = self.dataArr[indexPath.row];

     shoes.name = @"阿迪达斯";

     [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];

     NSLog(@"\n%p\n%p",&shoes,self.dataArr[indexPath.row]);

     

     [self.appdelegate saveContext];

     

#pragma mark - 归档

     student.booksArray = [NSKeyedArchiver archivedDataWithRootObject:@[book,book1]];

     //解归档

     NSArray *bookArr = [NSKeyedUnarchiver unarchiveObjectWithData:stu.booksArray];

     


     

#pragma mark - smallArr_?smallArr_:@"" A?A:@"" a是否为yes 是取a 否取@""

     

#pragma mark - 设置placehold的字体颜色

     

#pragma mark - 貌似是获取某控件上所有子视图的

     unsigned int count = 0;

     Ivar *property = class_copyIvarList([UITabBarItem class], &count);

     for (int i = 0; i < count; i++) {

         

         Ivar var = property[i];

         const char *name = ivar_getName(var);

         const char *type = ivar_getTypeEncoding(var);

         NSLog(@"%s =============== %s",name,type);

         

     }

     

#pragma mark - 设置tabbaritem角标

     #import "UITabBarItem+Badge.h"

     for (int i = 0; i<4; i++) {

         UITabBarItem *tabBarItemWillBadge = self.navigationController.tabBarController.tabBar.items[i];

         [tabBarItemWillBadge yee_MakeRedBadge:4 color:[UIColor redColor]];

     }

     //移除角标

     UITabBarItem *tabBarItemWillBadge = self.navigationController.tabBarController.tabBar.items[0];

     [tabBarItemWillBadge removeBadgeView];

     

     

#pragma mark 显示自定义角标

     /**

      *  在自定义UITabBarButton角标,必须在viewDidAppear:方法中调用,让其和系统的角标的中心重合.

      *

      *  @param itemNum 要把角标显示在第几个控制器上面

      *  @param width   角标的直径,默认为5.0

      */

     - (void)showBadgeInController:(NSInteger)itemNum width:(CGFloat)width

     {

         UITabBarController *tabBarVC = (UITabBarController*)appDelegate.window.rootViewController.tabBarController;

         tabBarVC = self.navigationController.tabBarController;

         //设置系统角标视图

         UITabBarItem *tabBarItemWillBadge = tabBarVC.tabBar.items[itemNum];

         

         tabBarItemWillBadge.badgeValue = @"";

         if (width <= 0) {

             width = 5.0;

         }

         

         //新建角标视图

         UIView *smallBadge = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, width)];

         smallBadge.backgroundColor = [UIColor redColor];

         smallBadge.layer.cornerRadius = smallBadge.bounds.size.width * 0.5;

         smallBadge.tag = 100099 + itemNum;

         

         //遍历查找含有系统角标的视图,用自定义的角标视图代替系统的角标视图.

         for (UIView *tabBarBtn in tabBarVC.tabBar.subviews) {

             for (UIView *tabBarBtnSubview in tabBarBtn.subviews) {

                 

                 NSString *strSubviewName = [NSString stringWithUTF8String:object_getClassName(tabBarBtnSubview)];

                 if ([strSubviewName isEqualToString:@"UITabBarButtonBadge"] ||

                     [strSubviewName isEqualToString:@"_UIBadgeView"]){

                     //添加自定义角标到按钮上,并移除系统角标

                     smallBadge.center = tabBarBtnSubview.center;

                     [tabBarBtn addSubview:smallBadge];

                     [tabBarBtnSubview removeFromSuperview];

                 }

             }

         }

     }

     

#pragma mark 移除自定义角标

     /**

      *  移除自定义UITabBarButton角标.

      *

      *  @param itemNum 要把第几个控制器上面的角标移除

      */

     - (void)removeBadgeInController:(NSInteger)itemNum

     {

         UITabBarController *tabBarVC = (UITabBarController*)appDelegate.window.rootViewController;

         //遍历查找并移除含有自定义角标的视图.

         for (UIView *tabBarBtn in tabBarVC.tabBar.subviews) {

             for (UIView *tabBarBtnSubview in tabBarBtn.subviews) {

                 

                 if ( tabBarBtnSubview.tag == 100099 + itemNum ){

                     [tabBarBtnSubview removeFromSuperview];

                     return;

                 }

             }

         }

     }

     

#pragma mark - 时间设置 智能处理时间显示

     messagee.strTime = [[NFbaseViewController new] timestampSwitchTime:1500363113 andFormatter:@"yyyy-MM-dd hh:mm:ss"];

     

#pragma mark - 当前时间转nsinter

     NSTimeInterval interval = [currentDate timeIntervalSince1970];

     //记录已读时间

     entity.localReceiveTime = interval;

     

     

#pragma mark - scoket请求

     //for 循环请求 当连接时候进行发送

     [self sendMessageWith:Json];

     

     -(void)sendMessageWith:(NSString *)json{

         if (socketModel.isConnected) {

             [socketModel sendMsg:json];

         }else{

             [self createDispatchWithDelay:0.2 block:^{

                 [self performSelector:@selector(sendMessageWith:) withObject:json];

             }];

         }

     }

     

#pragma mark - 消息提醒

     #import "FLStatusBarHUD.h"

     // 是否手动处理statusBar点击

     BOOL _clicked;

     // 隐藏开启与否

     BOOL _flag;

     // 是否自定义view

     BOOL _selected;

     

     FLAnimationDirection type = FLAnimationDirectionFromTop;

     [FLStatusBarHUD shareStatusBar].animationDirection = type;

     [FLStatusBarHUD shareStatusBar].statusBarHeight = 64;

     [FLStatusBarHUD shareStatusBar].messageDuration = 5;

     //当是自定义的view 这里设置则无效

     [FLStatusBarHUD shareStatusBar].messageColor = [UIColor redColor];

     [FLStatusBarHUD shareStatusBar].messageFont = [UIFont systemFontOfSize:9];

     [FLStatusBarHUD shareStatusBar].position = CGPointMake(0, 64);

     

     view = [[[NSBundle mainBundle]loadNibNamed:@"MessageView" owner:nil options:nil] firstObject];

     view.frame = CGRectMake(0, 64, 414, 50);

     view.titleLabel.text = @"小白:师傅我来啦!";

     view.titleLabel.textColor = [UIColor yellowColor];

     view.titleLabel.font = [UIFont systemFontOfSize:16];

     

     [[FLStatusBarHUD shareStatusBar] fl_showCustomView:view atView:self.view animateDirection:type autoDismiss:_flag];

     

     //搜索栏-拷贝

     [FLStatusBarHUD shareStatusBar].backgroundImage = [UIImage imageNamed:@"搜索栏-拷贝"];

     

     if (_clicked) {

         [FLStatusBarHUD shareStatusBar].statusBarTapOpreationBlock = ^{

             UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"点我啦" message:nil delegate:nil cancelButtonTitle:@"恩恩~" otherButtonTitles:nil];

             [alertView show];

         };

     }

     

     

#pragma mark - 排序

     //按照create_time降序,最上面是最近日期

     NSSortDescriptor *create_time = [NSSortDescriptor sortDescriptorWithKey:@"create_time" ascending:NO];

     

     

#pragma mark - 判断是否包含数字字母tonum

     -(int)checkIsHaveNumAndLetter:(NSString*)password{

         //数字条件

         NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];

         

         //符合数字条件的有几个字节

         NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:password

                                                                            options:NSMatchingReportProgress

                                                                              range:NSMakeRange(0, password.length)];

         

         //英文字条件

         NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];

         

         //符合英文字条件的有几个字节

         NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];

         

         if (tNumMatchCount == password.length) {

             //全部符合数字,表示沒有英文

             return 1;

         } else if (tLetterMatchCount == password.length) {

             //全部符合英文,表示沒有数字

             return 2;

         } else if (tNumMatchCount + tLetterMatchCount == password.length) {

             //符合英文和符合数字条件的相加等于密码长度

             return 3;

         } else {

             return 4;

             //可能包含标点符号的情況,或是包含非英文的文字,这里再依照需求详细判断想呈现的错误

         }

         

     }

     

     contact.friend_username_data = [[NFMyManage new] NumToString:contact.friend_username];

     

#pragma mark - 获取网络状态

     #import "SystemInfo.h"

     Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];

     NetworkStatus internetStatus = [reachability currentReachabilityStatus];

     if (internetStatus != NotReachable) {

         //有网

         isFromAutoLogin = YES;

         [self loginWithDefaultType];

     }else{

         

     }

     

#pragma mark - 状态栏

     //字体颜色

     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

     //背景颜色

     UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

     if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {

         statusBar.backgroundColor = [UIColor whiteColor];

     }

#pragma mark - 状态栏背景颜色

     UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

     //设置状态栏背景颜色

     if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {

         statusBar.backgroundColor = [UIColor clearColor];

     }

     

#pragma mark - zjcontact根据friend_username搜索

     resultController.data = [ZJContact searchText:searchText inDataArray:self.allData];

     [resultControlle

      

#pragma mark - 头像拼接

      NSURL *icon1URL = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/3816723-e182f6da029b3e7d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/100"] ;

      NSURL *icon2URL = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/3816723-023e66be11a2e94b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/100"];

      NSURL *icon3URL = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/3816723-d7ece9dba73d4953.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/100"] ;

      NSURL *icon4URL = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/3816723-e08bf975aadbfdd4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/100"] ;

      NSURL *icon5URL = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/3816723-13271b280c0e5fd4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/100"] ;

      NSArray *iconItemsArr = @[icon1URL,icon2URL,icon3URL,icon4URL,icon5URL];

      headImageView.image = [UIImage groupIconWithURLArray:iconItemsArr bgColor:[UIColor groupTableViewBackgroundColor]];

      

      

      

#pragma mark - 当编辑的时候 设置改变按钮颜色

      -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

          if (textField.tag == 1) {

              if (firstNewTextF.text.length && secNewTextFG.text.length && textField.text.length + string.length - range.length >0) {

                  [commitBtn setTitleColor:[UIColor colorThemeTintColor] forState:(UIControlStateNormal)];

                  [commitBtn setBackgroundColor:[UIColor colorThemeColor]];

                  return YES;

              }

          }else if (textField.tag == 2){

              if (OldPassWordTextF.text.length && secNewTextFG.text.length && textField.text.length + string.length - range.length >0) {

                  [commitBtn setTitleColor:[UIColor colorThemeTintColor] forState:(UIControlStateNormal)];

                  [commitBtn setBackgroundColor:[UIColor colorThemeColor]];

                  return YES;

              }

          }else if (textField.tag == 3){

              if (OldPassWordTextF.text.length && firstNewTextF.text.length && textField.text.length + string.length - range.length >0) {

                  [commitBtn setTitleColor:[UIColor colorThemeTintColor] forState:(UIControlStateNormal)];

                  [commitBtn setBackgroundColor:[UIColor colorThemeColor]];

                  return YES;

              }

          }

          [commitBtn setTitleColor:[UIColor colorThemeTintColor] forState:(UIControlStateNormal)];

          [commitBtn setBackgroundColor:[UIColor colorSectionHeader]];

          return YES;

      }

     

#pragma mark - image 转成字符串属性

      UIImage *image = [UIImage new];

      //创建附件对象

      NSTextAttachment * imageTextAttachment = [[NSTextAttachment alloc]init];

      //设置图片属性

      imageTextAttachment.image = image;

      //根据图片创建属性字符串

      NSAttributedString * imageAttributeString = [NSAttributedString attributedStringWithAttachment:imageTextAttachment];

      

      

#pragma mark - 拉伸图片 点九图

      normal = [UIImage imageNamed:@"chatfrom_bg_normal"];

      //上下左右距离图片多少尺寸 不被拉伸

      normal = [normal resizableImageWithCapInsets:UIEdgeInsetsMake(35, 22, 10, 10)];

      

      

#pragma mark - navagation底部线条颜色

      //方法一 不健壮

      [self.navigationBar setShadowImage:[self imageWithColor:[UIColor redColor] size:CGSizeMake([UIScreen mainScreen].bounds.size.width, 0.5)]];

      

      - (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {

          if (!color || size.width <= 0 || size.height <= 0) return nil;

          CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);

          UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);

          CGContextRef context = UIGraphicsGetCurrentContext();

          CGContextSetFillColorWithColor(context, color.CGColor);

          CGContextFillRect(context, rect);

          UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

          UIGraphicsEndImageContext();

          return image;

      }

      

      //方法二 健壮

      -(void)setNavigationBottomLineColor:(UIColor *)color{

          //先查看View层次结构

          //    NSLog(@"Navigationbar recursiveDescription:\n%@",[self.navigationBar performSelector:@selector(recursiveDescription)]);

          //打印完后我们发现有个高度为0.5的UIImageView 类型 SuperView type为 _UIBarBackground的视图

          //遍历navigationBar 属性

          unsigned int outCount = 0;

          Ivar *ivars = class_copyIvarList([self.navigationBar class], &outCount);

          for (NSInteger i = 0; i < outCount; ++i) {

              Ivar ivar = *(ivars + i);

              NSLog(@"navigationBar Propertys:\n name = %s  \n type = %s", ivar_getName(ivar),ivar_getTypeEncoding(ivar));

          }

          free(ivars);

          

          //遍历结果可以发现navigationbar 中的type 为_UIBarBackground 名称为 _barBackgroundView

          //遍历_barBackgroundView 中的属性

          unsigned int viewOutCount = 0;

          UIView *barBackgroundView = nil;

          /*iOS 10.0+为`_barBackgroundView`,小于iOS10.0这个属性名称为`_UIBarBackground`.*/

          

          if (UIDeviceCurrentDevice<10.0) {

              barBackgroundView = [self.navigationBar valueForKey:@"_backgroundView"];

          }else{

              barBackgroundView = [self.navigationBar valueForKey:@"_barBackgroundView"];

          }

          if (barBackgroundView) {

              Ivar *viewivars = class_copyIvarList([barBackgroundView class], &viewOutCount);

              for (NSInteger i = 0; i < viewOutCount; ++i) {

                  Ivar ivar = *(viewivars + i);

                  NSLog(@"_barBackgroundView Propertys:\n name = %s  \n type = %s", ivar_getName(ivar),ivar_getTypeEncoding(ivar));

              }

              free(viewivars);

          }

          //找到type为 UIImageView 的属性有_shadowView,_backgroundImageView。因为底部线条可以设置shadowImage,所有我们猜测是_shadowView

          UIImageView *navigationbarLineView = [barBackgroundView valueForKey:@"_shadowView"];

          if (navigationbarLineView && [navigationbarLineView isKindOfClass:[UIImageView class]]) {

              UIView *lineView = [[UIView alloc]init];

              lineView.backgroundColor = [UIColor redColor];

              lineView.translatesAutoresizingMaskIntoConstraints = NO;

              [navigationbarLineView addSubview:lineView];

              

              //这里我们要用约束不然旋转后有问题

              [navigationbarLineView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:navigationbarLineView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];

              

              [navigationbarLineView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:navigationbarLineView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];

              

              [navigationbarLineView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:navigationbarLineView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];

              

              [navigationbarLineView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:navigationbarLineView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];

          }

      }

      

#pragma mark - 改变tabbar顶部线颜色

      [self.tabBar setShadowImage:[self imageWithColor:[UIColor redColor] size:CGSizeMake(self.view.frame.size.width, .5)]];

      

      

#pragma mark - 表情判断

      BOOL ret = [ClearManager stringContainsEmoji:[[dataDict objectForKey:@"messageContent"] description]];

      - (BOOL)stringContainsEmoji:(NSString *)string

      {

          __block BOOL returnValue = NO;

          

          [string enumerateSubstringsInRange:NSMakeRange(0, [string length])

                                     options:NSStringEnumerationByComposedCharacterSequences

                                  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {

                                      const unichar hs = [substring characterAtIndex:0];

                                      if (0xd800 <= hs && hs <= 0xdbff) {

                                          if (substring.length > 1) {

                                              const unichar ls = [substring characterAtIndex:1];

                                              const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;

                                              if (0x1d000 <= uc && uc <= 0x1f77f) {

                                                  returnValue = YES;

                                              }

                                          }

                                      } else if (substring.length > 1) {

                                          const unichar ls = [substring characterAtIndex:1];

                                          if (ls == 0x20e3) {

                                              returnValue = YES;

                                          }

                                      } else {

                                          if (0x2100 <= hs && hs <= 0x27ff) {

                                              returnValue = YES;

                                          } else if (0x2B05 <= hs && hs <= 0x2b07) {

                                              returnValue = YES;

                                          } else if (0x2934 <= hs && hs <= 0x2935) {

                                              returnValue = YES;

                                          } else if (0x3297 <= hs && hs <= 0x3299) {

                                              returnValue = YES;

                                          } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {

                                              returnValue = YES;

                                          }

                                      }

                                  }];

          return returnValue;

      }

      

      

#pragma mark - 清除数据库缓存

      NSError *error;

      NSFileManager *fileManager = [NSFileManager defaultManager];

      //NSCachesDirectory  NSDocumentDirectory

      NSString  *cachPath = [ NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask ,  YES )  objectAtIndex : 0 ];

      NSArray *contents = [fileManager contentsOfDirectoryAtPath:cachPath error:NULL];

      for (NSString *path in contents) {

          if (![path containsString:@"mineSet"] ) {

              NSString *reallyPath = [NSString stringWithFormat:@"%@/%@",cachPath,path];

              if([fileManager fileExistsAtPath:reallyPath]){

                  [jqFmdb close];

                  long long size=[fileManager attributesOfItemAtPath:cachPath error:nil].fileSize;

                  BOOL success = [fileManager removeItemAtPath:cachPath error:&error];

                  BOOL create = [fileManager createDirectoryAtPath:cachPath withIntermediateDirectories:NO attributes:nil error:&error];

                  NSLog(@"");

              }

          }

          

      }

      NSArray *contentss = [fileManager contentsOfDirectoryAtPath:cachPath error:NULL];

      

#pragma mark - 扩大按钮点击范围【父视图必须足够大】

      [self.btnVoiceRecord setEnlargeEdgeWithTop:10 right:50 bottom:10 left:0];

      

      #import <objc/runtime.h>

      - (void)setEnlargeEdge:(CGFloat) size;//同下效果

      - (void)setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left;

      - (void)setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left

     {

         objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);

         objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);

         objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);

         objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);

     }

      

      - (CGRect)enlargedRect

     {

         NSNumber* topEdge = objc_getAssociatedObject(self, &topNameKey);

         NSNumber* rightEdge = objc_getAssociatedObject(self, &rightNameKey);

         NSNumber* bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);

         NSNumber* leftEdge = objc_getAssociatedObject(self, &leftNameKey);

         if (topEdge && rightEdge && bottomEdge && leftEdge)

         {

             return CGRectMake(self.bounds.origin.x - leftEdge.floatValue,

                               self.bounds.origin.y - topEdge.floatValue,

                               self.bounds.size.width + leftEdge.floatValue + rightEdge.floatValue,

                               self.bounds.size.height + topEdge.floatValue + bottomEdge.floatValue);

         }

         else

         {

             return self.bounds;

         }

     }

      - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event

     {

         CGRect rect = [self enlargedRect];

         if (CGRectEqualToRect(rect, self.bounds))

         {

             return [super pointInside:point withEvent:event];

         }

         return CGRectContainsPoint(rect, point) ? YES : NO;

     }

      

      

#pragma mark - 生成二维码

      #import <CoreImage/CoreImage.h>

      // 1. 创建一个二维码滤镜实例(CIFilter)

      CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

      // 滤镜恢复默认设置

      [filter setDefaults];

      // 2. 给滤镜添加数据

      NSString *string = Json;

      NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

      // 使用KVC的方式给filter赋值

      [filter setValue:data forKeyPath:@"inputMessage"];

      // 3. 生成二维码

      CIImage *image = [filter outputImage];

      UIImage *showImage = [[UIImage alloc] init];

      showImage = [self createNonInterpolatedUIImageFormCIImage:image withSize:showCodeView.frame.size.width];

      showCodeView.image = showImage;

      

      - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {

          CGRect extent = CGRectIntegral(image.extent);

          CGFloat scale = MIN(size/CGRectGetWidth(extent), size/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];

      }

      

#pragma mark - json转string

      NSString *Json = [JsonModel convertToJsonData:self.parms];

      NSDictionary *MsgDic = [JsonModel dictionaryWithJsonString:message];


      

#pragma mark - 判断都是空格

      NSString*temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

      if ([temp length] ==0) {

          [SVProgressHUD showInfoWithStatus:@"不能发送空消息"];

          return;

      }

      

#pragma mark - 获取当前控制器

      UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

      UIViewController *currentVC = [NFMyManage getCurrentVCFrom:rootViewController];

      if ([currentVC isKindOfClass:[DynamicNewDetailViewController class]]) {

          [NFUserEntity shareInstance].isNeedDeleteDidselectedPush = YES;

      }

      

#pragma mark  - 获取当前控制器

      UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

      UIViewController *currentVC = [NFMyManage getCurrentVCFrom:rootViewController];

      

#pragma mark - 图片拉伸方法

      #import "UIImage+SDResize.h"

      normal = [UIImage imageNamed:@"chatMyMessage_Normal"];

      normal = [UIImage SDResizeWithIma:normal];

      normalSelected = [UIImage imageNamed:@"chatMyMessage_Highlighted"];

      normalSelected = [UIImage SDResizeWithIma:normalSelected];

      

#pragma mark - 万能跳转 需要获取到根视图控制器 当需要跳转到服务器制定的任意控制器时

      //根据字符串获取类

      NSDictionary *params =@{@"class":@"QRCodeScanViewController"};

      // 类名

      NSString *classs =[NSString stringWithFormat:@"%@", params[@"class"]];

      const char *className = [classs cStringUsingEncoding:NSASCIIStringEncoding];

      // 从一个字串返回一个类

      Class newClass = objc_getClass(className);

      if (!newClass)

      {

          // 创建一个类

          Class superClass = [NSObject class];

          newClass = objc_allocateClassPair(superClass, className, 0);

          // 注册你创建的这个类

          objc_registerClassPair(newClass);

      }

      // 创建对象

      id instance = [[newClass alloc] init];

      // 对该对象赋值属性

      NSDictionary * propertys = params[@"property"];

      [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

         // 检测这个对象是否存在该属性

         if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {

             // 利用kvc赋值

             [instance setValue:obj forKey:key];

         }

     }];

      // 获取导航控制器

      //            UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;

      //            UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];

      //            // 跳转到对应的控制器

      //            [pushClassStance pushViewController:instance animated:YES];

      UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

      UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];

      [currentVC.navigationController pushViewController:instance animated:YES];

      

#pragma mark - nsdata转 base64字符串

      NSString *encodedVoiceStr = [dic[@"voice"] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

      

      //base64字符串 转  nsdata

      NSData *voiceData   = [[NSData alloc] initWithBase64Encoding:messagee.strContent];

      

#pragma mark - 三角关系取值

      entity.messageContant = entity.messageContant.length>1000?@"语音":entity.messageContant;

      

#pragma mark - SDImageCache 缓存图片

      //缓存图片

      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

      [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];

      [dateFormatter setDateFormat: @"yyyyMMddhhmmssSS"];

      NSString *identifier = [dateFormatter stringFromDate:[NSDate date]];

      entity.cachePicPath = [NSString stringWithFormat:@"%@%@",identifier,[NFUserEntity shareInstance].userId];

      [[SDImageCache sharedImageCache] diskImageExistsWithKey:entity.cachePicPath completion:^(BOOL isInCache) {

         if (!isInCache) {

             [[SDImageCache sharedImageCache] storeImage:[UIImage imageWithData:entity.pictureData] forKey:entity.cachePicPath toDisk:YES];

         }

     }];

      //去图片

      [[SDImageCache sharedImageCache] diskImageExistsWithKey:entity.cachePicPath completion:^(BOOL isInCache) {

         if (isInCache) {

             messagee.picture = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:entity.cachePicPath];

             //            messagee.picture = [UIImage imageWithData:entity.pictureData];

         }else{

             messagee.picture = [UIImage imageWithData:entity.pictureData];

         }

     }];

      

#pragma mark - UIMenuController

      点击需要弹出的按钮后

      [mineContantBtn becomeFirstResponder];

      UIMenuController *menu = [UIMenuController sharedMenuController];

      UIMenuItem * item1 = [[UIMenuItem alloc]initWithTitle:@"剪切" action:@selector(myCut:)];

      UIMenuItem * item2 = [[UIMenuItem alloc]initWithTitle:@"粘贴" action:@selector(myPaste:)];

      //            menu.menuItems = @[item1,item2];

      [menu setMenuItems:@[item1,item2]];

      [menu setTargetRect:mineContantBtn.frame inView:mineContantBtn.superview];

      [menu setMenuVisible:YES animated:YES];

      

      -(BOOL)canPerformAction:(SEL)action withSender:(id)sender{

          if (action == @selector(myCut:) || action == @selector(myPaste:)) {

              return YES;

          }

          //    return NO;

          return (action == @selector(copy:));

      }

      -(void)copy:(id)sender{

          if (!self.titleLabel.text) return;

          UIPasteboard *pboard = [UIPasteboard generalPasteboard];

          pboard.string = self.titleLabel.text;

      }

      -(void)myCut:(id)sender{

          if (!self.titleLabel.text) return;

          UIPasteboard *pboard = [UIPasteboard generalPasteboard];

          pboard.string = self.titleLabel.text;

      }

      -(void)myPaste:(id)sender{

          if (!self.titleLabel.text) return;

          UIPasteboard *pboard = [UIPasteboard generalPasteboard];

          pboard.string = self.titleLabel.text;

      }

      

#pragma mark - 取消按钮高亮s

      - (void)viewDidLoad {

          [super viewDidLoad];

          UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

          button.backgroundColor = [UIColor cyanColor];

          [button setTitle:@"+" forState:UIControlStateNormal];

          button.frame = CGRectMake(100, 64, 100, 30);

          [button setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];

          [self.view addSubview:button];

          [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

          //保证所有touch事件button的highlighted属性为NO,即可去除高亮效果

          [button addTarget:self action:@selector(preventFlicker:) forControlEvents:UIControlEventAllTouchEvents];

      }

      - (void)buttonTapped:(UIButton *)button {

          NSLog(@"touch up inside");

      }

      - (void)preventFlicker:(UIButton *)button {

          button.highlighted = NO;

      }

      

      

#pragma mark - 获取网络状态

      +(BOOL)getNetStatus{

          Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];

          NetworkStatus internetStatus = [reachability currentReachabilityStatus];

          if (internetStatus == NotReachable) {

              return NO;

          }

          return YES;

      }

      //调用

      [ClearManager getNetStatus]

      

      

#pragma mark - map

      //拉入GaoDeMap 文件夹 framework

      //工程plist加入allowlocation

      //工程勾选locationupdates

      //依赖库QuartzCore, CoreLocation, SystemConfiguration, CoreTelephony, libz,libstdc++6.09, Security。

      //

      //编译报警,看看添加的framework 在buildingseting中有没有添加

      //appdelagate中设置 【这个appkey需要在高德配置 账号15861882350 密码名字1129】

      [MAMapServices sharedServices].apiKey = @"ce3a62595f7dfb2670910465c12e90f5";

      


      

#pragma mark - 条转webview

      #import "NewsWebViewController.h"

      NewsWebViewController *toCtrol = [[NewsWebViewController alloc] init];

      toCtrol.title = @"彩票";

      toCtrol.newsURL = @"https://down.updateapp-down.com/";

      [self.navigationController pushViewController:toCtrol animated:YES];

      

      首页中

      MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

      hud.labelText = @"加载中";

      AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];

      manger.responseSerializer = [AFHTTPResponseSerializer serializer];

      [manger GET:@"https://appid-ios.zz-app.com/frontApi/getAboutUs" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

         

     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

         NSError *error;

         id object = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:&error];

         if (error) {

             //            hud.labelText = @"数据序列化失败";

         }else{

             hud.labelText = @"加载成功";

             if ([object isKindOfClass:[NSDictionary class]]) {

                 NSLog(@"%@",object);

                 NSDictionary *returnDict = object;

                 id str = [returnDict objectForKey:@"status"];

                 NSLog(@"%@",[str class]);

                 if ([[[returnDict objectForKey:@"status"] description] isEqualToString:@"1"]) {

                     NewsWebViewController *toCtrol = [[NewsWebViewController alloc] init];

                     toCtrol.title = @"彩票";

                     toCtrol.newsURL = @"https://down.updateapp-down.com/";

                     [self.navigationController pushViewController:toCtrol animated:YES];

                     return ;

                 }else if ([[[returnDict objectForKey:@"status"] description] isEqualToString:@"0"]){

                     NSLog(@"未通");

                 }else if ([[[returnDict objectForKey:@"status"] description] isEqualToString:@"2"]){

                     NSLog(@"关闭");

                 }

             }

         }

         [hud hide:YES afterDelay:0.5];

         

     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

         //        hud.labelText = @"加载失败";

         [hud hide:YES afterDelay:0.5];

     }];

      

      

#pragma mark - MBProgress

#import "MBProgressHUD+NHAdd.h"

      if ([SVProgressHUD isVisible]) {

          [MBProgressHUD showTitleToView:self.view postion:NHHUDPostionBottom title:@"请勿重复操作!"];

          return;

      }

      

      

      

#pragma mark - APP之间跳转

      //在各自的target的info中设置schemeURL

      //在infoPlist中设置LSApplicationQueriesSchemes 添加对方的item

      //发送方

      -(void)pushToAPPName:(NSString *)toName myAPPName:(NSString *)fromName FirstParameterString:(NSString *)firstParameter SecondParameterString:(NSString *)secondParameter{

          NSString *Json = [NSString stringWithFormat:@"appName:%@,appId:%@",fromName,firstParameter];

          NSURL *appBUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@",toName,Json]];

          if ([[UIApplication sharedApplication] canOpenURL:appBUrl]) {

              // 3. 打开应用程序App-B

              [[UIApplication sharedApplication] openURL:appBUrl];

          } else {

              NSLog(@"没有安装");

          }

      }

      //接收方

      -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{

          

          NSString *canshu = url.absoluteString;

          NSArray *arr = [canshu componentsSeparatedByString:@"//"];

          NSString *keyString = arr[1];

          NSArray *keyArr = [keyString componentsSeparatedByString:@","];

          NSMutableDictionary *sendDict = [NSMutableDictionary new];

          for (NSString *info in keyArr) {

              NSArray *infoArr = [info componentsSeparatedByString:@":"];

              [sendDict setObject:infoArr[1] forKey:infoArr[0]];

          }

          return NO;

      }

      

      //接收方处理完后 进行跳转回去 不需要设置白名单

      [[UIApplication sharedApplication] openURL:appBUrl options:nil completionHandler:^(BOOL success) {

         NSLog(@"");

     }];

      

      

#pragma mark - 判断手机有没有在安装某个软件

      if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {

          NSLog(@"canopen");

      }

      if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]]) {

          NSLog(@"canopen");

      }

      

#pragma mark - tableview优化

      #import "SDAutoLayout.h"

      

      //在setentity的setup中设置

      //控件布局

      _showMoreBtn.sd_layout

      .leftEqualToView(headImageView)

      .topSpaceToView(contentLabel, margin)

      .rightSpaceToView(self.contentView, margin)

      .bottomEqualToView(contentLabel, margin)

      .centerXEqualToView(self.contentView, margin)

      .centerYEqualToView(contentLabel, margin)

      .widthIs(40)

      .heightIs(20);

      .autoHeightRatio(0); //设置label frame相对于父视图倍率 设置0 将根据文字自适应宽高,

      //随即设置是否展开

      if (entity_.isExetend)

      {

          contentLabel.sd_layout.maxHeightIs(MAXFLOAT);

          [_showMoreBtn setTitle:@"收起" forState:UIControlStateNormal];

      }else

      { contentLabel.sd_layout.maxHeightIs(maxContentLabelHeight);

          [_showMoreBtn setTitle:@"展开" forState:UIControlStateNormal];

      }

      

#pragma mark - 布局

      //*labell的父视图是label,下面可以设置labell在父视图的UIEdgeInsetsMake

      labell.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));

      //*labell的父视图是label,下面可以设置label自适应labell高度 bottom间距为0【如果label相对于labell的y为10,那么label设置后高度将比labell高出10】

      //父视图相对于子视图 底部缩进或超出bottomMargin

      [label setupAutoHeightWithBottomView:labell bottomMargin:0];

      //取array中最后 最下面的view 作为bottomview

      [label setupAutoHeightWithBottomViewsArray:@[labell,labelll] bottomMargin:10];

      //父视图相对于子视图 右边缩进或超出rightMargin

      [label setupAutoWidthWithRightView:labell rightMargin:100];

      //** labell左边到其参照view之间的间距,参数为“(View 或者 view数组, CGFloat)”  */

      labell.sd_layout.leftSpaceToView(label, 10);

      labell.sd_layout.rightSpaceToView(label, 10);

      labell.sd_layout.topSpaceToView(label, 10);

      labell.sd_layout.bottomSpaceToView(label, 10);

      //labell相对于父视图 x、y、centreX、centreY的位置

      labell.sd_layout.xIs(10);

      labell.sd_layout.yIs(10);

      labell.sd_layout.centerXIs(100);

      labell.sd_layout.centerYIs(50);

      labell.sd_layout.widthIs(100);

      labell.sd_layout.heightIs(100);

      /** 更新cell内部的控件的布局(cell内部控件专属的更新约束方法,如果启用了cell frame缓存则会自动清除缓存再更新约束) */

      updateLayoutWithCellContentView

      

      //设置button内的文字 左右文字间距为Padding前提下 自适应宽度

      [button setupAutoSizeWithHorizontalPadding:30 buttonHeight:20];

      

      

      

#pragma mark - tableHeaderView上拉后不回弹

      NSMutableDictionary *rowHeightCache;

      rowHeightCache = [NSMutableDictionary new];

      

      heightForRowAtIndexPath中

      if ([rowHeightCache objectForKey:[NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row]]) {

          NSNumber *cacheHeight = [rowHeightCache objectForKey:[NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row]];

          return [cacheHeight floatValue];

      }

      CGFloat height = [OnlyTextTableViewCell getContentCellHeight:entity.circle_content seeingMore:entity.isExetend];

      NSNumber *cacheHeight = [[NSNumber alloc] initWithFloat:height];

      [rowHeightCache setValue:cacheHeight forKey:[NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row]];

      //计算总高度

      -(CGFloat)cellsTotalHeight:(NSDictionary *)dict{

          CGFloat totalHeight = 0;

          NSArray *heightValues = [dict allValues];

          for (NSNumber *cacheHeight in heightValues) {

              totalHeight +=[cacheHeight floatValue];

          }

          return totalHeight;

      }

      //当滑动完

      -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

          NSLog(@"%f",self.tableView.contentOffset.y);

          CGFloat height = [self cellsTotalHeight:rowHeightCache] + (_sectionIndexs.count - 1)*20 + 50;

          if (self.tableView.contentOffset.y > 0 && height <= SCREEN_HEIGHT - kTopHeight - kTabBarHeight) {

              [UIView animateWithDuration:0.1 animations:^{

                  self.tableView.contentOffset = CGPointMake(0, 0);

              }];

          }

      }

      

      

#pragma mark - 获取udid

      #import <AdSupport/AdSupport.h>

      包含AdSupport库

  NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

  NSString *ipStringV6 = [self getIPAddress:NO];

  NSString *ipStringV4 = [self getIPAddress:YES];

      

      

#pragma mark - 识别相册

      //传入图片。传出二维码中的信息

      - (NSString *)readQRCodeInfoFromImage:(UIImage *)image

     {

         NSData *imageData = UIImageJPEGRepresentation(image, 1);

         CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];

         CIImage *ciImage = [CIImage imageWithData:imageData];

         NSArray *ar = [detector featuresInImage:ciImage];

         CIQRCodeFeature *feature = [ar firstObject];

         NSLog(@"context: %@", feature.messageString);

         return feature.messageString;

     }

      

#pragma mark - 三方库突然找不到头文件

      ~/Library/Developer/Xcode/DerivedData 删除文件

      

      [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];

      [SVProgressHUD setBackgroundColor:[UIColor redColor]];

      [SVProgressHUD setForegroundColor:[UIColor blueColor]];

      [SVProgressHUD setBackgroundLayerColor:[UIColor yellowColor]];

      

      

      

#pragma mark - 懒加载

      @property (copy, nonatomic) NSMutableDictionary *cacheDataRowSendStatus;    //懒加载

      

      //懒加载

      -(NSMutableDictionary *)cacheDataRowSendStatus{

          if (!_cacheDataRowSendStatus) {

              _cacheDataRowSendStatus = [[NSMutableDictionary alloc] init];

          }

          return _cacheDataRowSendStatus;

      }

      

      [self.cacheDataRowSendStatus removeAllObjects];

      [self.cacheDataRowSendStatus setObject:entity.message.appMsgId forKey:[NSString stringWithFormat:@"%@-%@",indexPath.section,indexPath.row]];

      [self.cacheDataRowSendStatus objectForKey:[NSString stringWithFormat:@"%@-%@",indexPath.section,indexPath.row]];

      

      NSString*temp = [info stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

      if (temp.length == 0) {

          [SVProgressHUD showInfoWithStatus:@"名字不能为空"];

          return;

      }

      

#pragma mark - 如果没有某类 则xcode报警

      //如果GQImageViewrBaseURLRequest文件丢失或者未加入当前target则会抛出此异常

      if (!NSClassFromString(@"GQImageViewrBaseURLRequest")) {

          NSAssert(0, @"GQImageViewrBaseURLRequest class is miss, please check!");

      }

      

      

#pragma mark - SDWebImage 常用

      SDWebImageManager *webImageManager = [SDWebImageManager sharedManager];

      [webImageManager diskImageExistsForURL:imageUrl completion:^(BOOL isInCache) {

         if (isInCache) {

             image = [webImageManager.imageCache imageFromDiskCacheForKey:urlString];

         }

     }];

      

      //查看聊天图片

#import "GQImageViewer.h"

#import "UIImage+GQImageViewrCategory.h"

#import "GQImageDataDownload.h"

#import "LWWeChatActionSheet.h"


      

      

#pragma mark - 查看聊天记录所有图片

      JQFMDB *jqFmdb;

      

-(void)lookSingleCachePictureArrWithFriendId:(NSString *)friendId IsSelf:(BOOL)ret{

  jqFmdb = [JQFMDB shareDatabase:@"tongxun.sqlite"];

  NSArray *imageChatEntityArr = [jqFmdb jq_lookupTable:friendId dicOrModel:[MessageChatEntity class] whereFormat:@"where type = '%@'",@"1"];

  NSMutableArray *urlArr = [NSMutableArray new];

  NSInteger selectedIndex = 0;

  BOOL IsSearched = NO;

  for (MessageChatEntity *picEntity in imageChatEntityArr) {

      if (picEntity.pictureUrl.length > [NFUserEntity shareInstance].HeadPicpathAppendingString.length && ![picEntity.yuehouYinCang isEqualToString:@"1"]) {

          [urlArr addObject:picEntity.pictureUrl];

          if (!IsSearched && [picEntity.pictureUrl isEqualToString:self.messageFrame.message.pictureUrl]) {

              selectedIndex = urlArr.count -1;

              IsSearched = YES;

          }

      }

  }

  GQWeakify(self);

  //链式调用

  [GQImageViewer sharedInstance]

  .configureChain(^(GQImageViewrConfigure *configure) {

      [configure configureWithImageViewBgColor:[UIColor blackColor]

                               textViewBgColor:nil

                                     textColor:[UIColor whiteColor]

                                      textFont:[UIFont systemFontOfSize:12]

                                 maxTextHeight:100

                                textEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)

                                     scaleType:GQImageViewerScaleTypeEqualWidth

                               launchDirection:GQLaunchDirectionFromRect];

      //        [configure setRequestClassName:@"GQImageViewrBaseURLRequest"];

      [configure setNeedPanGesture:NO];//设置是否需要滑动消失手势

      configure.usePageControl = NO;

      if (ret) {

          configure.launchFromView = mineContantBtn;

      }else{

          configure.launchFromView = otherContantBtn;

      }

      configure.textViewBgColor = [UIColor clearColor];//底部view颜色【显示pagecontrol或pageLabel的】

      [configure setNeedTapAutoHiddenTopBottomView:YES];//设置是否需要自动隐藏顶部和底部视图

  })

  //    .dataSouceArrayChain(imageArray,textArray)//如果仅需要图片浏览就只需要传图片即可,无需传文字数组

  .dataSouceArrayChain(urlArr,nil)//如果仅需要图片浏览就只需要传图片即可,无需传文字数组

  //    .selectIndexChain(index)//设置选中的索引

  .topViewConfigureChain(^(UIView *configureView) {

      //        configureView.height = 80;

      //        configureView.backgroundColor = [UIColor cyanColor];

      //        [weak_self topViewAddLabelText:@"手动管理生命周期" withTopView:configureView];

      //        UIButton *button = [weak_self creatButtonWithTitle:@"点击消失" withSEL:@selector(dissMissImageViewer:)];

      //        button.frame = CGRectMake(10, (configureView.height - 30) / 2, 100, 30);

      //        [configureView addSubview:button];

  })

  .bottomViewConfigureChain(^(UIView *configureView) {

      //        configureView.height = 50;

      //        configureView.backgroundColor = [UIColor yellowColor];

  })

  .achieveSelectIndexChain(^(NSInteger selectIndex){//获取当前选中的图片索引

      NSLog(@"滑动到某一张事件");

  })

  .longTapIndexChain(^(UIImage *image , NSInteger selectIndex){//长按手势回调

      NSLog(@"长按事件");

      LWWeChatActionSheet *sheet = [[LWWeChatActionSheet alloc] initWithWeChatActionSheetCancelButtonTitle:@"取消" title:nil otherButtonTitles:[NSArray arrayWithObjects:@"保存图片", nil] btnClickBlock:^(NSInteger buttonIndex) {

          if (buttonIndex == 0) {

              NSLog(@"保存图片");

              UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);

          }

      }];

      [sheet show];

  })

  .dissMissChain(^(){

      NSLog(@"dissMiss");

  })

  .singleTapChain(^(NSInteger selectIndex){

      NSLog(@"单击事件");

      [[GQImageViewer sharedInstance] dissMissWithAnimation:YES];

  })

  .showInViewChain([KeepAppBox viewController:self].view.window,YES);//显示GQImageViewer到指定view上

  //setSelectIndex

  [[GQImageViewer sharedInstance] setSelectIndex:selectedIndex];//设置选中的索引

  

}

#pragma mark - 保存图片成功失败代理

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo

{

 if (!error) {

     [SVProgressHUD showSuccessWithStatus:@"已保存到系统相册"];

 }else{

     [SVProgressHUD showErrorWithStatus:@"保存失败"];

 }

 NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);

 

}

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

#pragma mark - 唐巧方法

      //label中文字居上

- (void)alignTop {

  CGSize fontSize = [self.text sizeWithFont:self.font];

  double finalHeight = fontSize.height * self.numberOfLines;

  double finalWidth = self.frame.size.width;    //expected width of label

  CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];

  int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;

  for(int i=0; i<newLinesToPad; i++)

      self.text = [self.text stringByAppendingString:@"\n "];

}

      //label中文字居下

- (void)alignBottom {

  CGSize fontSize = [self.text sizeWithFont:self.font];

  double finalHeight = fontSize.height * self.numberOfLines;

  double finalWidth = self.frame.size.width;    //expected width of label

  CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];

  int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;

  for(int i=0; i<newLinesToPad; i++)

      self.text = [NSString stringWithFormat:@" \n%@",self.text];

}

      

#pragma mark - addChildViewController方法后 需要调用addChildViewController将childview add到self.view上

   苹果新的 API 增加了 addChildViewController 方法,并且希望我们在使用 addSubview 时,同时调用 [self addChildViewController:child] 方法将 sub view 对应的 viewController 也加到当前 ViewController 的管理中。对于那些当前暂时不需要显示的 subview,只通过 addChildViewController 把 subViewController 加进去。需要显示时再调用 transitionFromViewController:toViewController:duration:options:animations:completion 方法。

//另外,当收到系统的 Memory Warning 的时候,系统也会自动把当前没有显示的 subview unload 掉,以节省内存。

      

#pragma mark - 获取控件相对于屏幕位置

      UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];

      [textField convertRect: textField.bounds toView:win]

      

#pragma mark - 当键盘出现的时候,如何让UITextField自动上移  继承tableviewController不需要考虑

      //方法一

      -(void)viewWillAppear:(BOOL)animated{

          [super viewWillAppear:YES];

          [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];

          [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];

      }

      

      -(void)viewWillDisappear:(BOOL)animated{

          [super viewWillDisappear:YES];

          [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

          [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

      }

      

      //方法二 【推荐】

      #define kOFFSET_FOR_KEYBOARD 215

      -(void)textFieldDidBeginEditing:(UITextField *)textField{

          UIWindow *win = [[[UIApplication sharedApplication] windows] firstObject];

          //如果编辑的textfield被键盘遮挡的话那么就上移

          if (SCREEN_HEIGHT - CGRectGetMaxY([textField convertRect: textField.bounds toView:win]) < kOFFSET_FOR_KEYBOARD) {

              [self setViewMovedUp:YES];

          }

      }

      

      -(void)textFieldDidEndEditing:(UITextField *)textField{

          [self setViewMovedUp:NO];

      }

      

      -(void)setViewMovedUp:(BOOL)movedUp

     {

         [UIView beginAnimations:nil context:NULL];

         [UIView setAnimationDuration:0.5]; // if you want to slide up the view

         CGRect rect = self.view.frame;

         if (movedUp)

         {

             rect.origin.y -= kOFFSET_FOR_KEYBOARD;

             rect.size.height += kOFFSET_FOR_KEYBOARD;

         }

         else

         {

             //        rect.origin.y += kOFFSET_FOR_KEYBOARD;

             //        rect.size.height -= kOFFSET_FOR_KEYBOARD;

             rect.origin.y = 0;

             rect.size.height = SCREEN_HEIGHT;

         }

         self.view.frame = rect;

         [UIView commitAnimations];

     }

      

#pragma mark - 将数组中的实体按照某属性排序

      NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(name)];

      

#pragma mark - 系统文字语言 设置应用内的系统控件语言

      <key>CFBundleLocalizations</key>

      <array>

      <string>zh_CN</string>

      <string>en</string>

      </array>

      

#pragma mark - 将文本设置成以单词换行

      NSString *content = @"";

      content = [content stringByReplacingOccurrencesOfString:@" " withString:@" "];

      

      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值