在UITableViewController里面实现UITextField与键盘的自适应

Posted on 2014-07-01 13:12  cillyfly  阅读(457)  评论(0编辑  收藏  举报

tableview里面对textfield的键盘适应本身就是逻辑实现,利用下面代理函数将textfield的位置移到最优点。

	//将活跃的textview移动到tableview的中间
		- (void)textFieldDidBeginEditing:(UITextField*)textField
		{
		    UITableViewCell* cell = [self parentCellFor:textField];
		    if (cell)
		    {
		        NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
		        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
		    }
		}

	//结束textview的编辑时将tableview移动到原来的位置
		- (void)textFieldDidEndEditing:(UITextField*)textField
		{
		    UITableViewCell* cell = [self parentCellFor:textField];
		    if (cell)
		    {
		        NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
		        [self textFieldDidEndEditing:textField inRowAtIndexPath:indexPath];
		        [self.tableView reloadRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationNone];
		    }
		}

	//寻找当前cell在tableview中的位置 
		- (UITableViewCell*)parentCellFor:(UIView*)view
		{
		    if (!view)
		        return nil;
		    if ([view isMemberOfClass:[UITableViewCell class]])
		        return (UITableViewCell*)view;
		    return [self parentCellFor:view.superview];
		}

以上方法可以有效的使得tableview中的textview正确的移动位置