OC编程中通知的使用2(监听)

来源:互联网 发布:淘宝如何设置拍下立减 编辑:程序博客网 时间:2024/06/06 05:11
设计一个APP,必不可少的就是让用户输入一些信息,那么键盘的弹出收回问题也就接踵而来,因为有可能输入框会在键盘弹出时被掩盖,这个时候我们该怎么办呢?再有就是我们需要做到及时通信,比如我们在一个界面点击了取消订单按钮,则上一个界面就应立马显示订单已取消的样式。这个时候使用通知监听键盘弹出收回、事件触发就能很好地解决这个问题了。
1、键盘监听
当我们界面中有很多输入框时:
首先声明一个属性接收用户当前编辑的是哪一个输入框:

@property (nonatomic,strong)UITextField *currentField;//当前输入框//添加观察者监听键盘的弹出收回[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(up:) name:UIKeyboardWillShowNotification object:nil];//键盘将要出现时[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(down:) name:UIKeyboardWillHideNotification object:nil];//键盘将要收回时

当然我们还需要遵守UITextField的代理方法UITextFieldDelegate(可选实现)

//实现代理方法

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ self.currentField = textField;//每次点到一个输入框就让它保留到currentField中return YES;//支持编辑}

//可以在这个方法里限制输入框的输入内容

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{    if (range.location >= 10 || textField.text.length + string.length >= 10) {        return NO;//不允许改变    }    return YES;//允许改变    //识别邮箱、特殊字符过滤}

//实现键盘通知方法

- (void)up:(NSNotification *)info{    NSLog(@"%@",info);//键盘参数    NSDictionary *userInfo = info.userInfo;    CGRect keyBoardFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];//获取信息字典中的键盘的高    CGFloat height = keyBoardFrame.size.height;//动态的键盘高度    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;//屏幕的高    CGFloat dy = screenHeight - height - self.currentField.frame.origin.y -self.currentField.frame.size.height;    NSLog(@"dy = %f",dy);    if (dy < 0) {   //当输入框位置低于键盘时        [UIView animateWithDuration:0.7 animations:^{            self.view.center = CGPointMake(self.view.center.x, dy + screenHeight/2.0);        }];    }}

//键盘收回

- (void)down:(NSNotification *)info{    [UIView animateWithDuration:0.7 animations:^{        self.view.center = CGPointMake(self.view.center.x, [UIScreen mainScreen].bounds.size.height/2);//使得view回到屏幕中心    }];}

//点界面上任意地方使得键盘弹回

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [self.currentField resignFirstResponder];//取消第一响应,键盘弹回}

//同样,记得移除通知

- (void)sealloc{    [[NSNotificationCenter defaultCenter] removeObserver:self];//移除所有通知事件}

2、监听响应事件

界面二点击取消订单按钮,界面一及时响应事件,设置该订单的状态为已取消

//界面一注册监听中心 

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

//界面二点击Button事件中发送通知(注意name)

//这里的nil也可以是需要传输的数据[[NSNotificationCenter defaultCenter] postNotificationName:@"clickCancle" object:nil];

//界面一通知事件

- (void) changeState:(NSNotification *)info{//改变状态代码在这里编写,就可以及时的改变状态了}

//界面一移除通知

- (void)sealloc{    [[NSNotificationCenter defaultCenter] removeObserver:self];//移除所有通知事件}




0 0
原创粉丝点击