UITableView的删除、添加,dataPick的使用


#import "waterFlowerViewController.h"


#import "AFHTTPRequestOperationManager.h"

#import "MBProgressHUD.h"

#import "ServiceManager.h"


@interface waterFlowerViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

{

    UIButton *datyButton;

    UIView *bgView;

    

    NSArray *numberList;//总的num

    

    UIDatePicker *datePicker;

    

    UITextField *timeF;//时间

    

    NSMutableArray *resultList;//有效的结果

    

    NSInteger minNum;//最小的NUM

    

    NSString *number;//按钮上的数

    

    

    UITableView *myTableView;

    

    NSString *pid;

    NSString *tok;

    

    

}

@end


@implementation waterFlowerViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    

    self.title = @"浇水时间段设置";

    number = @"1";

    numberList = @[@"1",@"2",@"3",@"4",@"5"];

    [self createVC];


    //增加监听,当键盘出现或改变时收出消息

    [[NSNotificationCenter defaultCenter] addObserver:self

       selector:@selector(keyboardWillShowChange:) name:UIKeyboardWillShowNotification object:nil];

    

    //增加监听,当键退出时收出消息

    [[NSNotificationCenter defaultCenter] addObserver:self

      selector:@selector(keyboardWillHideChange:)name:UIKeyboardWillHideNotification object:nil];

  

}


#pragma mark------每次进来 出去设备上的当前时间段

- (void)viewWillAppear:(BOOL)animated

{

    ServiceManager *_servicemanger = [ServiceManager sharedManager];

    pid =  _servicemanger.dic[@"PID"];

    tok = _servicemanger.dic[@"TOKEN"];

    

    if (pid != nil) {

        

        NSString *urlStr = @"http://218.240.133.170:85/Mob?";

        

        

        

        NSDictionary *parameter = @{@"PID":pid,@"TOK":tok,@"MARK":@"1",@"TAG":@"GAC2"};

        

        NSLog(@"++++++%@",parameter);

        

        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

        NSMutableArray *mutAry = [NSMutableArray array];

        

        [manager POST:urlStr parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSDictionary *dics = responseObject;

            NSLog(@"----------%@",dics);

            

            if ([dics[@"REST"] isEqualToString:@"true"]) {

                

                NSArray *array = dics[@"TABLE"];

                

                

                for (NSDictionary *dic in array) {

                    NSLog(@"+++++ %@",dic);

                    //取已经有天数的时间段

                    if ([dic[@"VAL"] isEqualToString:@"1"] || [dic[@"VAL"] isEqualToString:@"2"] || [dic[@"VAL"] isEqualToString:@"3"] || [dic[@"VAL"] isEqualToString:@"4"] ||

                        [dic[@"VAL"] isEqualToString:@"5"]) {

                        [mutAry addObject:dic];

                    }

                }

                resultList = mutAry;

                

                [myTableView reloadData];

                

            }else{

                

                [self showSimple:[dics[@"ERR"] substringFromIndex:6]];

                

                

                

            }

            

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            

            [self showSimple:@"网络断开连接"];

        }];


    }else{

    [self showSimple:@"设备不能为空"];

    }

    

   

}


//监听键盘弹出时的高度 并修改self.view frame

-(void)keyboardWillShowChange:(NSNotification *)keyboard

{

    NSDictionary *dic = [keyboard userInfo];

    

    float height = [[dic objectForKeyedSubscript:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;

    

    self.view.frame = CGRectMake(self.view.frame.origin.x, 0-height, self.view.frame.size.width, self.view.frame.size.height);

    

}

//监听键盘收复时的高度 并修改self.view frame

-(void)keyboardWillHideChange:(NSNotification *)keyboard{

    

    self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);

    

}


//取消键盘

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

{

    [timeF resignFirstResponder];

}



#pragma  mark-----创建UI

- (void)createVC

{

    

    UIButton * backBtn=[[UIButton alloc]initWithFrame:CGRectMake(5, 20, 60,44 )];

    [backBtn setTitle:@"<返回" forState:(UIControlStateNormal)];

    

    [backBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

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

    [self.view addSubview:backBtn];

    

    

  //创建顶部导航栏视图

    UILabel *tapLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 44)];

    

    tapLable.layer.borderWidth = 1;

    tapLable.layer.borderColor = [UIColor lightGrayColor].CGColor;

    tapLable.text = @"浇水时间段设置";

    tapLable.textAlignment = NSTextAlignmentCenter;

    [self.view addSubview:tapLable];

    

    //创建UITableView

    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(tapLable.frame), CGRectGetWidth(self.view.bounds), 300-44)];

    myTableView.dataSource = self;

    myTableView.delegate = self;

    myTableView.scrollEnabled = NO;

    [self.view addSubview:myTableView];

    

    //起始时间

    CGFloat timeFY = CGRectGetMaxY(myTableView.frame)+50;

    timeF = [[UITextField alloc]initWithFrame:CGRectMake(20, timeFY, 100, 40)];

    timeF.delegate = self;

    timeF.borderStyle = UITextBorderStyleRoundedRect;

    timeF.layer.cornerRadius = 4;

//    timeF.enabled = NO;

    timeF.placeholder = @"起始时间";

    timeF.layer.masksToBounds = YES;

    [self.view addSubview:timeF];

    

    //添加一个时间选择器

    datePicker= [[UIDatePicker alloc]init];

    [datePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];

     datePicker.datePickerMode = UIDatePickerModeTime;

    //当光标移动到文本框的时候,召唤时间选择器

    [datePicker addTarget:self action:@selector(datePickerAction:) forControlEvents:UIControlEventValueChanged];

     timeF.inputView = datePicker;

    

    

    

    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];

    CGFloat addBtnW = 30;

    CGFloat addBtnH = 30;

    CGFloat addBtnX = CGRectGetWidth(self.view.bounds)-30-addBtnW;

    

    //添加按钮

    addButton.frame = CGRectMake(addBtnX, timeFY+5, addBtnW, addBtnH);

//    addButton.backgroundColor = [UIColor redColor];

    [addButton setImage:[UIImage imageNamed:@"adddevice"] forState:UIControlStateNormal];

    [addButton addTarget:self action:@selector(addActionData:) forControlEvents:UIControlEventTouchUpInside];

    addButton.showsTouchWhenHighlighted = YES;

    [self.view addSubview:addButton];

    

    //间隔天数

    CGFloat intervalLH = CGRectGetMaxY(addButton.frame)+20;

    UILabel *intervalL = [[UILabel alloc]initWithFrame:CGRectMake(20, intervalLH, 80, 30)];

    intervalL.text = @"间隔天数:";

    intervalL.textAlignment = NSTextAlignmentLeft;

    [self.view addSubview:intervalL];

    

    

    //天数选择按钮

    datyButton = [UIButton buttonWithType:UIButtonTypeCustom];

    CGFloat datyBtnX = CGRectGetMaxX(intervalL.frame)+10;

    datyButton.frame = CGRectMake(datyBtnX, intervalLH, 40, 30);

//    datyButton.backgroundColor = [UIColor redColor];

    [datyButton setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];

    [datyButton addTarget:self action:@selector(datyAction:) forControlEvents:UIControlEventTouchUpInside];

    [datyButton setTitle:number forState:UIControlStateNormal];

    [datyButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

    datyButton.showsTouchWhenHighlighted = YES;

    [self.view addSubview:datyButton];

}


#pragma mark--------返回

- (void)backBtnAction

{

    [self.navigationController popViewControllerAnimated:NO];

}


#pragma mark-------监听datePicker的变化

- (void)datePickerAction:(UIDatePicker *)sender

{

  [timeF resignFirstResponder];

    

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

   formatter.dateFormat = @"HH:mm";

    

    NSString *str = [formatter stringFromDate:sender.date];

    timeF.text = [NSString stringWithFormat:@"%@:00",str];

}


#pragma mark---------右侧加号按钮的触发事件

- (void)addActionData:(UIButton *)btn

{

    NSMutableArray *newArray = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

    

    if (timeF.text.length != 0) {//如果左侧的值为空

        if (resultList.count < 5) {//已经添加的设备数少于5

            

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

            

              //  遍历已经存在的数组

                for (int j = 0; j < newArray.count; j++) {//遍历总的num数组

                    

                    if ([resultList[i][@"NUM"] isEqualToString:newArray[j]]) {

                    //总数的nunm减去已经存在的nun`

                    [newArray removeObjectAtIndex:j];

//                    [surplusList addObject:numberList[j]];

                        

                        

                    }

                }

            }

            

            minNum = [newArray[0] integerValue];//最小的num

            for (int k = 0; k < newArray.count; k++) {

                if ([newArray[k] integerValue] < minNum) {

                    //取出数组里面最小的NUM

                    minNum = [newArray[k] integerValue];

                    

                }

                

            }

          

            //添加定时时间

            

            NSString *minStr =  [NSString stringWithFormat:@"%ld",minNum];

            NSLog(@"NUM == %@",minStr);

          

             ServiceManager *_servicemanger = [ServiceManager sharedManager];

            

          

            

            [self addTimeWithPID:_servicemanger.dic[@"PID"] andTOK:_servicemanger.dic[@"TOKEN"] andNUM:minStr andSTART:timeF.text andVAL:number];

            

        }else{

        [self showSimple:@"亲,定时数大于5"];

        

        }

        

    }else{

         [self showSimple:@"亲,时间不可为空"];

    }

}


#pragma mark ---------添加定时时间

- (void)addTimeWithPID:(NSString *)pidStr andTOK:(NSString *)tokStr andNUM:(NSString *)numStr andSTART:(NSString *)startStr andVAL:(NSString *)valStr

{

    if (pid != nil) {

        NSString *urlStr = @"http://218.240.133.170:85/Mob?";

        NSDictionary *parameter = @{@"PID":pidStr,@"MARK":@"1",@"TOK":tokStr,@"TAG":@"AC2",@"NUM":numStr,@"START":startStr,@"VAL":valStr};

        

        NSLog(@"++++++%@",parameter);

        

        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

        [manager POST:urlStr parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSDictionary *dics = responseObject;

            NSLog(@"----------%@",dics);

            

            if ([dics[@"REST"] isEqualToString:@"true"]) {

                

                [resultList addObject:parameter];

                

                NSLog(@"parameter=%@",parameter);

                NSLog(@"resultList=%@",resultList);

                

                

                [myTableView reloadData];

                

                

            }else{

                [self showSimple:[dics[@"ERR"] substringFromIndex:6]];

            }

            

            

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            

            [self showSimple:@"网络断开连接"];

        }];

    }else{

    [self showSimple:@"设备不能为空"];

    }


}


#pragma mark------操作成功显示视图

- (IBAction)showSimple:(NSString *)sender {

    

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    hud.mode = MBProgressHUDModeText;

    hud.labelText = sender;

    hud.margin = 10.f;

    hud.removeFromSuperViewOnHide = YES;

    hud.yOffset = 180;

    [hud hide:YES afterDelay:1];

    

}



#pragma mark---------天数选择按钮触发事件

- (void)datyAction:(UIButton *)sender

{

    if (sender.selected == NO || bgView == nil) {

        

        CGFloat bgViewX = CGRectGetMinX(datyButton.frame);

        CGFloat bgViewW = 25;

        CGFloat bgViewH = 30*5+4;

        CGFloat bgViewY = CGRectGetMinY(datyButton.frame)-bgViewH;

        

        bgView = [[UIView alloc]initWithFrame:CGRectMake(bgViewX, bgViewY, bgViewW, bgViewH)];

        bgView.backgroundColor = [UIColor lightGrayColor];

        [self.view  addSubview:bgView];

        sender.selected = YES;

        

        

        for (int i = 0; i < numberList.count-1; i++) {

            UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 30+30*i, bgViewW, 1)];

            lineV.backgroundColor = [UIColor whiteColor];

            [bgView addSubview:lineV];

        }

        

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

          UIButton *numberBtn = [UIButton buttonWithType:UIButtonTypeCustom];

          numberBtn.frame = CGRectMake(0, 30*i, bgViewW, 30);

          [numberBtn setTitle:numberList[i] forState:UIControlStateNormal];

            numberBtn.tag = 600 + i;

          [numberBtn addTarget:self action:@selector(numberAction:) forControlEvents:UIControlEventTouchUpInside];

            [numberBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

          numberBtn.showsTouchWhenHighlighted = YES;

          [bgView addSubview:numberBtn];

        }

        

        

    }else{

        [bgView removeFromSuperview];

        bgView = nil;

        sender.selected = NO;

    }

    

}


#pragma mark---------序号按钮触发事件

- (void)numberAction:(UIButton *)sender

{

        number = [NSString stringWithFormat:@"%d",sender.tag-600+1];

        

        [datyButton setTitle:number forState:UIControlStateNormal];

        [bgView removeFromSuperview];

        bgView = nil;

   

    

    

}


#pragma mark---------UITableView的代理

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

{

    return resultList.count;

    

}

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

{

   static NSString *cellID = @"cellID";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

       

    }

    

    

    NSString *text = [NSString stringWithFormat:@"%ld    %@-%@",indexPath.row + 1,resultList[indexPath.row][@"START"],resultList[indexPath.row][@"VAL"]];

    NSLog(@"#############%@",text);

    cell.textLabel.text = text;

    return cell;

}


//要求委托方的编辑风格在表视图的一个特定的位置。

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;//默认没有编辑风格

    if ([tableView isEqual:myTableView]) {

        result = UITableViewCellEditingStyleDelete;//设置编辑风格为删除风格

    }

    return result;

}


-(void)setEditing:(BOOL)editing animated:(BOOL)animated{//设置是否显示一个可编辑视图的视图控制器。

    [super setEditing:editing animated:animated];

    [myTableView setEditing:editing animated:animated];//切换接收者的进入和退出编辑模式。

}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{//请求数据源提交的插入或删除指定行接收者。

    if (editingStyle ==UITableViewCellEditingStyleDelete) {//如果编辑样式为删除样式

        

        if (indexPath.row < resultList.count ) {

            if (tok != nil && pid != nil) {

                

                NSString *deleteNumStr = resultList[indexPath.row][@"NUM"];

                

                

                NSString *urlStr = @"http://218.240.133.170:85/Mob?";

                

                

                NSDictionary *parameter = @{@"PID":pid,@"MARK":@"1",@"TOK":tok,@"TAG":@"AC2",@"NUM":deleteNumStr,@"START":@"",@"VAL":@""};

                

                NSLog(@"++++++%@",parameter);

                

                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

                [manager POST:urlStr parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

                    NSDictionary *dics = responseObject;

                    NSLog(@"----------%@",dics);

                    

                    if ([dics[@"REST"] isEqualToString:@"true"]) {

                        

                        

                        //                     NSLog(@"indexPath.row= %ld resultList = %d",indexPath.row,resultList.count);

                        

                        if (indexPath.row != resultList.count) {

                            [resultList removeObjectAtIndex:indexPath.row];//移除数据源的数据

                            

                            //                        NSLog(@"indexPath.row= %ld resultList2 = %d",indexPath.row,resultList.count);

                            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据

                            

                            [myTableView reloadData];

                        }

                        

                    }else{

                        

                        [self showSimple:[dics[@"ERR"] substringFromIndex:6]];

                        

                    }

                    

                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

                    

                    [self showSimple:@"网络连接失败"];

                }];


            }

         

        }

    }

}





- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/*

#pragma mark - Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值