ios 自定义cell中有textField,点击textField时,防止键盘挡住textField

来源:互联网 发布:有没有淘宝内部优惠券 编辑:程序博客网 时间:2024/04/30 21:23

自定义cell中的代码:
.h中设置一个代理

@protocol moveDelegate <NSObject>-(void)CellWith:(NSIndexPath * )index;//将点击的那个textField所在的cell,在tableView中的位置传到控制器界面@end@interface QuotedListTableViewCell : UITableViewCell<UITextFieldDelegate>@property (nonatomic, assign)id<moveDelegate> delegate;@end

.m文件中在textField被点击时,就进行代理的容错处理

- (void)textFieldDidBeginEditing:(UITextField *)textField {    if (self.delegate && [self.delegate respondsToSelector:@selector(CellWith:)]) {        [self.delegate CellWith:_flag];//_flag是在(- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中传过来的indexPath)    }}

控制器中代码

//实现代理  将textField所在的cell的indexPath传过来,并由indexPath获取到cell距离屏幕的顶端的距离-(void)CellWith:(NSIndexPath *)index {        CGRect rectInTableView = [_quotedTable rectForRowAtIndexPath:index];        CGRect rectInSuperview = [_quotedTable convertRect:rectInTableView toView:[_quotedTable superview]];   _rectCell = rectInSuperview;//_rectCell为定义的一个全局的变量//@property (nonatomic, assign)CGRect rectCell;}
- (void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillhidden: ) name:UIKeyboardWillHideNotification object:nil];}
//当键盘出现或改变时调用- (void)keyboardWillShow:(NSNotification *)aNotification{    //获取键盘的高度    NSDictionary *userInfo = [aNotification userInfo];    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];    CGRect keyboardRect = [aValue CGRectValue];    _keyBoardHeight = keyboardRect.size.height;    NSLog(@"键盘高度%f",_keyBoardHeight);    float textY = _rectCell.origin.y;//cell距离顶部的距离    float bottomY = self.view.bounds.size.height - textY;//要编辑的textField离底部的距离    NSLog(@"cell距离顶部的距离%f",textY);    NSLog(@"要编辑的textField离底部的距离%f",bottomY);    NSLog(@"%f",BOUNDS.size.height);    if (bottomY >= _keyBoardHeight) {        return;    }    _height = _keyBoardHeight-bottomY+40;//要移动的距离    NSLog(@"要移动的距离%f",_height);    [UIView animateWithDuration:0.5f animations:^{        self.view.frame = CGRectMake(0, (0-_height),  self.view.bounds.size.width, self.view.bounds.size.height);    }];}
//点击return键盘弹回的时候,view回到原来的位置-(BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    return YES;}
0 0
原创粉丝点击