在tableView中监听cell上textField的点击:
如下图:
-
方案一:如何确定点击的
cell
在tableView
中的frame
苹果API中有关于点击
cell
时获取cell
在tableView
中的位置的方法:
CGRect cellFrame = [tableView rectForRowAtIndexPath:indexPath];
在tableView
的点击方法中调用,获取cell
的frame
,textField
在cell
上,得到cell
的frame
就近似的得到textField
的frame
,但是cell
上的textField
会拦截这个点击,不能得到当前点击的textField
的frame
。故只能采用方案二。 -
方案二:如何确定
cell
上的textField在tableView
中的frame
首先textField
在cell
上,要获得textField在tableView
中的fram
,就只能采用convert
的方式,将textField
在cell上
的坐标转换到在tableView
上的坐标。
如何得到textField
的frame
,在cell
中将textField
的frame
传递出来:
//textfield的代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[textField setNeedsDisplay];
if (self.clickTextfieldBlock) {
self.clickTextfieldBlock(textField.frame);
}
return YES;
}
在tableView
中获取textField
的frame
,并转换坐标系:
__weak typeof(cell)weakCell = cell;
[cell setClickTextfieldBlock:^(CGRect textfieldFrame) {
__strong typeof(weakCell)strongCell = weakCell;
self.textfieldFrame = [strongCell convertRect:textfieldFrame toView: tableView];
}];
声明textfieldFrame
属性,用于在监听键盘的方法中进行比较。
键盘的监听方法:
- (void)keyboardFrameChange:(NSNotification *)note
{
NSDictionary *userInfo = note.userInfo;
CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat offset = self.textfieldFrame.origin.y + textField的高度 + textField和cell的间隔 - keyboardFrame.origin.y;
if (offset > 0) {
[self.tableView setContentOffset:CGPointMake(0, offset) animated:YES];
}else{
[self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}
}