2013-08-01 3 views
4

У меня есть контроллер представления, на котором у меня есть представление таблицы, в виде таблицы каждая строка имеет текстовое поле, когда я нажимаю на клавиатуру текстового поля и скрываю вид таблицы, а затем не вижу редактирование, как я могу исправить эту проблему? Я поставил наблюдатель, что зафиксировать выравнивание зрения контроллера, но он не работает здесь код ..Keyboard hide Проблема UITableView

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ 

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillShow:) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 
return YES; 
} 

-(void)keyboardWillShow { 
// Animate the current view out of the way 
[UIView animateWithDuration:0.3f animations:^ { 
    self.viewFrame = CGRectMake(0, -160, 320, 480); 
}]; 
} 
+0

u необходимо установить contentOffset –

+0

Эй, проверьте мой ответ. – NightFury

ответ

2
you have to write below code, it will hide and show keyboard. 

====>.h file: declare one UITextField as below: 

UITextField *actifText; 

====>.m file: 

-(void)viewDidAppear:(BOOL)animated 
{ 
    // Register notification when the keyboard will be show 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillShow:) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

// Register notification when the keyboard will be hide 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillHide:) 
              name:UIKeyboardWillHideNotification 
              object:nil]; 
} 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{    
[textField resignFirstResponder]; 
return YES; 
} 

-(void)viewDidDisappear:(BOOL)animated 
{ 
[[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

-(void) keyboardWillShow:(NSNotification *)note 
{ 
// Get the keyboard size 
CGRect keyboardBounds; 
[[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds]; 

// Detect orientation 
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
CGRect frame = self.tblName.frame; 

// Start animation 
[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationBeginsFromCurrentState:YES]; 
[UIView setAnimationDuration:0.3f]; 

// Reduce size of the Table view 
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) 
    frame.size.height -= keyboardBounds.size.height; 
else 
    frame.size.height -= keyboardBounds.size.width; 

// Apply new size of table view 
self.tblName.frame = frame; 

// Scroll the table view to see the TextField just above the keyboard 
if (self.actifText) 
{ 
    CGRect textFieldRect = [self.tblName convertRect:self.actifText.bounds fromView:self.actifText]; 
    [self.tblName scrollRectToVisible:textFieldRect animated:NO]; 
} 

[UIView commitAnimations]; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
self.actifText = nil; 
} 
- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    self.actifText = textField; 
} 

-(void) keyboardWillHide:(NSNotification *)note 
{ 
// Get the keyboard size 
CGRect keyboardBounds; 
[[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds]; 

// Detect orientation 
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
CGRect frame = self.tblName.frame; 

[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationBeginsFromCurrentState:YES]; 
[UIView setAnimationDuration:0.3f]; 

// Reduce size of the Table view 
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) 
    frame.size.height += keyboardBounds.size.height; 
else 
    frame.size.height += keyboardBounds.size.width; 

// Apply new size of table view 
self.tblName.frame = frame; 

[UIView commitAnimations]; 
} 
+0

его работа, но когда я нажимаю на текстовый вид, который находится в верхней части табличного вида, тогда представление таблицы перемещается вверх каждый раз, когда я нажимаю на текстовый вид. – Anu

+0

код написан для этого, потому что, если данные больше, в то время это будет я автоматически двигаю вверх. если вы этого не хотите, то удалите // Прокрутите представление таблицы, чтобы увидеть TextField чуть выше клавиатуры if (self.actifText) { CGRect textFieldRect = [self.tblName convertRect: self.actifText.bounds fromView: self.actifText ]; [self.tblName scrollRectToVisible: textFieldRect animated: NO]; } из - (void) клавиатураWillShow: (NSNotification *) примечание метод – Mital

0

При нажатии на какое-то текстовое поле внутри ячейки, вы должны знать indexpath текущей ячейки, так что, когда клавиатура отображается , вы можете сфокусировать его.

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField 
{ 
    UITableViewCell *cell = (UITableViewCell *)[textField superview].superview; 
    NSIndexPath *idxPath = [table indexPathForCell:cell]; 
    selectedIndex = idxPath.row;//instance variable 

    return YES; 
} 

-(void)keyboardWillShow { 

[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; 

} 

добавить также следующую строку ViewDidLoad, имея в виду, чтобы наблюдать, когда клавиатура появились. Если вы используете UIKeyboardWillShowNotification, будет вызван первый keyboardWillShow, а затем textFieldShouldBeginEditing:, что неверно.

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillShow:) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 

и установить

textfield.delegate = self; 

в cellForRowAtIndexPath при создании TextField. Он будет вызывать требуемые методы.