Fare una pergamena UITableView quando è selezionato campo di testo

voti
228

Dopo un sacco di tentativi ed errori, sto dando e chiedendo la domanda. Ho visto un sacco di persone con problemi simili, ma non riesco a ottenere tutte le risposte a lavorare bene.

Ho un UITableViewche si compone di cellule personalizzate. Le cellule sono fatte di 5 campi di testo accanto all'altro (come una sorta di griglia).

Quando provo a scorrere e modificare le celle in fondo il UITableView, non riesco a trovare le mie cellule correttamente posizionati sopra la tastiera.

Ho visto molte risposte parlando di cambiare dimensioni vista, ecc ... ma nessuno di loro ha funzionato bene finora.

Qualcuno potrebbe chiarire il modo giusto di fare questo con un esempio di codice concreto?

È pubblicato 27/02/2009 alle 11:05
fonte dall'utente
In altre lingue...                            


48 risposte

voti
110

Se si utilizza invece di UITableViewController UIViewController, verrà automaticamente farlo.

Risposto il 21/09/2010 a 04:42
fonte dall'utente

voti
89

La funzione che fa lo scorrimento potrebbe essere molto più semplice:

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    UITableViewCell *cell;

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
    // Load resources for iOS 6.1 or earlier
        cell = (UITableViewCell *) textField.superview.superview;

    } else {
        // Load resources for iOS 7 or later
        cell = (UITableViewCell *) textField.superview.superview.superview; 
       // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
    }
    [tView scrollToRowAtIndexPath:[tView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

Questo è tutto. Nessun calcolo a tutti.

Risposto il 15/04/2009 a 13:21
fonte dall'utente

voti
65

Sto facendo qualcosa di molto simile è generico, non c'è bisogno di calcolare qualcosa di specifico per il codice. Basta controllare le osservazioni sul codice:

in MyUIViewController.h

@interface MyUIViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
{
     UITableView *myTableView;
     UITextField *actifText;
}

@property (nonatomic, retain) IBOutlet UITableView *myTableView;
@property (nonatomic, retain) IBOutlet UITextField *actifText;

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;
- (IBAction)textFieldDidEndEditing:(UITextField *)textField;

-(void) keyboardWillHide:(NSNotification *)note;
-(void) keyboardWillShow:(NSNotification *)note;

@end

in MyUIViewController.m

@implementation MyUIViewController

@synthesize myTableView;
@synthesize actifText;

- (void)viewDidLoad 
{
    // 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];
}

// To be link with your TextField event "Editing Did Begin"
//  memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.actifText = textField;
}

// To be link with your TextField event "Editing Did End"
//  release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.actifText = nil;
}

-(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.myTableView.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.myTableView.frame = frame;

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

    [UIView commitAnimations];
}

-(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.myTableView.frame;

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

    // Increase 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.myTableView.frame = frame;

    [UIView commitAnimations];
}

@end

Swift 1.2+ Versione:

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var activeText: UITextField!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillShow:"),
            name: UIKeyboardWillShowNotification,
            object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillHide:"),
            name: UIKeyboardWillHideNotification,
            object: nil)
    }

    func textFieldDidBeginEditing(textField: UITextField) {
        activeText = textField
    }

    func textFieldDidEndEditing(textField: UITextField) {
        activeText = nil
    }

    func keyboardWillShow(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height -= keyboardSize.height
            tableView.frame = frame
            if activeText != nil {
                let rect = tableView.convertRect(activeText.bounds, fromView: activeText)
                tableView.scrollRectToVisible(rect, animated: false)
            }
            UIView.commitAnimations()
        }
    }

    func keyboardWillHide(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height += keyboardSize.height
            tableView.frame = frame
            UIView.commitAnimations()
        }
    }
}
Risposto il 13/04/2010 a 15:46
fonte dall'utente

voti
41

Ho avuto lo stesso problema, ma ho notato che appare solo in un'unica vista. Così ho cominciato a cercare le differenze tra i controllori.

Ho scoperto che il comportamento di scorrimento si trova in - (void)viewWillAppear:(BOOL)animateddel super istanza.

Quindi, essere sicuri di realizzare in questo modo:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // your code
}

E non importa se si utilizza UIViewControllero UITableViewController; controllato inserendo un UITableViewcome una visualizzazione secondaria di self.view nel UIViewController. E 'stato lo stesso comportamento. La vista non ha permesso di scorrere se la chiamata [super viewWillAppear:animated];mancava.

Risposto il 29/05/2011 a 01:42
fonte dall'utente

voti
37

io possa aver perso questo, come non ho letto tutto il post qui, ma quello che mi è venuta sembra ingannevolmente semplice. Non ho messo questo sotto torchio, testando in tutte le situazioni, ma sembra come dovrebbe funzionare bene.

regolare semplicemente la contentInset del Tableview per l'altezza della tastiera e quindi scorrere la cella verso il basso:

- (void)keyboardWasShown:(NSNotification *)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.myTableView.contentInset = contentInsets;
    self.myTableView.scrollIndicatorInsets = contentInsets;

    [self.myTableView scrollToRowAtIndexPath:self.currentField.indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

e naturalmente

- (void)keyboardWasHidden:(NSNotification *)aNotification
{
    [UIView animateWithDuration:.3 animations:^(void) 
    {
        self.myTableView.contentInset = UIEdgeInsetsZero;
        self.myTableView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }];
}

è questo troppo semplice? mi sto perdendo qualcosa? finora si sta lavorando per me va bene, ma come ho detto, non l'ho messo sotto torchio ...

Risposto il 18/08/2012 a 01:12
fonte dall'utente

voti
35

La soluzione più semplice per Swift 3 , sulla base di soluzione Bartłomiej Semańczyk :

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(CreateEditRitualViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(CreateEditRitualViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

// MARK: Keyboard Notifications

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardHeight = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {
        tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2, animations: {
        // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
    })
}
Risposto il 08/12/2016 a 13:26
fonte dall'utente

voti
34

Se è possibile utilizzare UITableViewController, si ottiene la funzionalità gratuitamente. A volte, tuttavia, questo non è un'opzione, in particolare se avete bisogno di più punti di vista non solo il UITableView.

Alcune delle soluzioni presentate qui non funzionano su iOS ≥4, alcuni non funzionano su iPad o in modalità orizzontale, alcuni non funzionano per le tastiere Bluetooth (dove non vogliamo alcun scorrimento), alcuni non lo fanno funzionare quando la commutazione tra più campi di testo. Quindi, se si sceglie una soluzione, assicuratevi di testare questi casi. Questa è la soluzione che utilizziamo usato in InAppSettingsKit :

- (void)_keyboardWillShow:(NSNotification*)notification {
    if (self.navigationController.topViewController == self) {
        NSDictionary* userInfo = [notification userInfo];

        // we don't use SDK constants here to be universally compatible with all SDKs ≥ 3.0
        NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
        if (!keyboardFrameValue) {
            keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
        }

        // Reduce the tableView height by the part of the keyboard that actually covers the tableView
        CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
        if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
            windowRect = IASKCGRectSwap(windowRect);
        }
        CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
        if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
            viewRectAbsolute = IASKCGRectSwap(viewRectAbsolute);
        }
        CGRect frame = _tableView.frame;
        frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
        [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        _tableView.frame = frame;
        [UIView commitAnimations];

        UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
        NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];

        // iOS 3 sends hide and show notifications right after each other
        // when switching between textFields, so cancel -scrollToOldPosition requests
        [NSObject cancelPreviousPerformRequestsWithTarget:self];

        [_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
}

- (void) scrollToOldPosition {
  [_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)_keyboardWillHide:(NSNotification*)notification {
    if (self.navigationController.topViewController == self) {
        NSDictionary* userInfo = [notification userInfo];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
        [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        _tableView.frame = self.view.bounds;
        [UIView commitAnimations];

        [self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
    }
}   

Ecco il codice completo della classe in InAppSettingsKit. Per provarlo, utilizzare il riquadro bambino "Lista Completa" dove è possibile testare gli scenari di cui sopra.

Risposto il 13/12/2010 a 17:01
fonte dall'utente

voti
34

Penso che è venuta in mente la soluzione per abbinare il comportamento di applicazioni di Apple.

In primo luogo, nella vostra viewWillAppear: iscriviti alle notifiche della tastiera, in modo da sapere quando la tastiera mostrare e nascondere, e il sistema vi dirà la dimensione della tastiera, ma non lo' dimenticare di annullare la registrazione della tua viewWillDisappear :.

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

Implementare i metodi simili al di sotto in modo da regolare la dimensione del vostro tableView per abbinare l'area visibile una volta che gli spettacoli della tastiera. Qui sto monitoraggio dello stato della tastiera separatamente in modo da poter scegliere quando per impostare il tableView di nuovo a tutta altezza me stesso, dato che si ottiene queste notifiche su ogni cambio di campo. Non dimenticare di implementare keyboardWillHide: e scegliere un posto opportuno fissare la dimensione tableView.

-(void) keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    if (keyboardIsShowing == NO)
    {
        keyboardIsShowing = YES;
        CGRect frame = self.view.frame;
        frame.size.height -= keyboardHeight;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

Ora qui è il bit di scorrimento, lavoriamo fuori un paio di taglie, poi vediamo dove siamo nella zona visibile, e impostare il rettangolo che vogliamo scorrere fino a essere o visualizzazione a metà sopra o sotto il centro del campo di testo base da dove si trova nella vista. In questo caso, abbiamo un array di UITextFields e un enum che tiene traccia di loro, quindi moltiplicando il rowHeight dal numero di riga ci dà l'offset del telaio in questa visualizzazione esterno effettivo.

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    CGFloat rowHeight = self.tableView.rowHeight;
    if (textField == textFields[CELL_FIELD_ONE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_ONE;
    }
    else if (textField == textFields[CELL_FIELD_TWO])
    {
        frame.origin.y += rowHeight * CELL_FIELD_TWO;
    }
    else if (textField == textFields[CELL_FIELD_THREE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_THREE;
    }
    else if (textField == textFields[CELL_FIELD_FOUR])
    {
        frame.origin.y += rowHeight * CELL_FIELD_FOUR;
    }
    CGFloat viewHeight = self.tableView.frame.size.height;
    CGFloat halfHeight = viewHeight / 2;
    CGFloat midpoint = frame.origin.y + (textField.frame.size.height / 2);
    if (midpoint < halfHeight)
    {
        frame.origin.y = 0;
        frame.size.height = midpoint;
    }
    else
    {
        frame.origin.y = midpoint;
        frame.size.height = midpoint;
    }
    [self.tableView scrollRectToVisible:frame animated:YES];
}

Questo sembra funzionare abbastanza bene.

Risposto il 23/03/2009 a 02:49
fonte dall'utente

voti
22

La soluzione più semplice per Swift :

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar?.becomeFirstResponder()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillShow(_:)), name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillHide(_:)), name: UIKeyboardDidHideNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.size.height {
            tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    UIView.animateWithDuration(0.2, animations: { self.table_create_issue.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) })
    // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
    }
Risposto il 25/08/2015 a 06:42
fonte dall'utente

voti
6

Spero che voi ragazzi già una soluzione di lettura di tutti coloro. Ma ho trovato la mia soluzione come segue. Mi aspetto che si dispone già di una cella con UITextField. Quindi, sulla preparazione solo a mantenere l'indice di riga nel tag del campo di testo.

cell.textField.tag = IndexPath.row;

Crea activeTextField, un'istanza di UITextFieldcon portata globale, come di seguito:

@interface EditViewController (){

    UITextField *activeTextField;

}

Così, ora basta copiare incollare il mio codice alla fine. E inoltre non dimenticare di aggiungereUITextFieldDelegate

#pragma mark - TextField Delegation

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

    activeTextField = textField;

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    activeTextField = nil;

}

tastiera registri notifications

#pragma mark - Keyboard Activity

- (void)registerForKeyboardNotifications

{

    [[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(keyboardWasShown:)

                                             name:UIKeyboardDidShowNotification object:nil];



    [[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(keyboardWillBeHidden:)

                                             name:UIKeyboardWillHideNotification object:nil];



}

Maniglie tastiera Notifications:

Chiamato quando il UIKeyboardDidShowNotificationviene inviato.

- (void)keyboardWasShown:(NSNotification*)aNotification

{

    NSDictionary* info = [aNotification userInfo];

    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

    NSIndexPath *currentRowIndex = [NSIndexPath indexPathForRow:activeTextField.tag inSection:0];

    [self.tableView scrollToRowAtIndexPath:currentRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

Chiamato quando il UIKeyboardWillHideNotificationviene inviato

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

}

Ora una cosa è di sinistra, Chiamare il registerForKeyboardNotificationsmetodo a ViewDidLoadmetodo come segue:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Registering keyboard notification

    [self registerForKeyboardNotifications];

    // Your codes here...

}

Si è fatto, spero che la tua textFieldsvolontà non è più nascosto dalla tastiera.

Risposto il 03/01/2015 a 21:36
fonte dall'utente

voti
6

Combinando e riempire gli spazi vuoti da più risposte (in particolare Ortwin Gentz, utente 98013) e un altro post, questo funzionerà out of the box per SDK 4.3 su un iPad in modalità verticale o orizzontale:

@implementation UIView (FindFirstResponder)
- (UIResponder *)findFirstResponder
{
  if (self.isFirstResponder) {        
    return self;     
  }

  for (UIView *subView in self.subviews) {
    UIResponder *firstResponder = [subView findFirstResponder];
    if (firstResponder != nil) {
      return firstResponder;
    }
  }

  return nil;
}
@end

@implementation MyViewController

- (UIResponder *)currentFirstResponder {
  return [self.view findFirstResponder];
}

- (IBAction)editingEnded:sender {
  [sender resignFirstResponder];
}

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

- (void)textFieldDidBeginEditing:(UITextField *)textField {
  UITableViewCell *cell = (UITableViewCell*) [[textField superview] superview];
  [_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillShow:(NSNotification*)notification {
  if ([self currentFirstResponder] != nil) {
    NSDictionary* userInfo = [notification userInfo];

    // we don't use SDK constants here to be universally compatible with all SDKs ≥ 3.0
    NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
    if (!keyboardFrameValue) {
      keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
    }

    // Reduce the tableView height by the part of the keyboard that actually covers the tableView
    CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
    CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
    CGRect frame = _tableView.frame;
    if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
      windowRect = CGRectMake(windowRect.origin.y, windowRect.origin.x, windowRect.size.height, windowRect.size.width);
      viewRectAbsolute = CGRectMake(viewRectAbsolute.origin.y, viewRectAbsolute.origin.x, viewRectAbsolute.size.height, viewRectAbsolute.size.width);
    }
    frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    _tableView.frame = frame;
    [UIView commitAnimations];

    UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
    NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];

    // iOS 3 sends hide and show notifications right after each other
    // when switching between textFields, so cancel -scrollToOldPosition requests
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    _topmostRowBeforeKeyboardWasShown = [[_tableView indexPathsForVisibleRows] objectAtIndex:0];
    [_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  }
}

- (void) scrollToOldPosition {
  [_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification {
  if ([self currentFirstResponder] != nil) {

    NSDictionary* userInfo = [notification userInfo];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    _tableView.frame = self.view.bounds;
    [UIView commitAnimations];

    [self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
  }
}   

@end
Risposto il 03/08/2011 a 03:35
fonte dall'utente

voti
5

Il mio approccio:

Io prima sottoclasse UITextField e aggiungi una proprietà indexPath. Nel cellFor ... Metodo consegno la proprietà indexPath.

Poi aggiungo seguente codice:

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:textField.indexPath];

CGPoint cellPoint = [cell convertPoint:textField.center toView:self.tableView];
[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, cellPoint.y-50);}];

al textFieldShould / WillBegin ... ecc.

Quando la tastiera scompare bisogna invertire con:

[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, 0);}];
Risposto il 29/09/2012 a 13:03
fonte dall'utente

voti
4

Utilizzare UITextField's delegateil metodo:

veloce

func textFieldShouldBeginEditing(textField: UITextField) -> bool {
  let txtFieldPosition = textField.convertPoint(textField.bounds.origin, toView: yourTableViewHere)
  let indexPath = yourTablViewHere.indexPathForRowAtPoint(txtFieldPosition)
  if indexPath != nil {
     yourTablViewHere.scrollToRowAtIndexPath(indexPath!, atScrollPosition: .Top, animated: true)
  }
  return true
}

Objective-C

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
  CGPoint txtFieldPosition = [textField convertPoint:CGPointZero toView: yourTablViewHere];
  NSLog(@"Begin txtFieldPosition : %@",NSStringFromCGPoint(txtFieldPosition));
  NSIndexPath *indexPath = [yourTablViewHere indexPathForRowAtPoint:txtFieldPosition];

  if (indexPath != nil) {
     [yourTablViewHere scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  }
  return YES;
}
Risposto il 20/03/2015 a 07:00
fonte dall'utente

voti
4

La risposta giusta è la risposta di Sam Ho:

"Se si usa UITableViewController invece di UIViewController, verrà automaticamente farlo"..

Basta fare in modo di collegare l'UITableView alla proprietà TableView del UITableViewController (quindi ad esempio non aggiungerlo come una visualizzazione secondaria della proprietà Vista del UITableViewController).

Assicuratevi anche di impostare la proprietà AutoresizingMask del UITableView a FlexibleHeight

Risposto il 09/12/2010 a 11:28
fonte dall'utente

voti
4

Se si utilizza Three20, quindi utilizzare la autoresizesForKeyboardproprietà. Basta impostare la vostra del controller della vista -initWithNibName:bundlemetodo

self.autoresizesForKeyboard = YES

Questo si occupa di:

  1. Ascolto per notifiche tastiera e regolando la cornice della vista tabella
  2. Scorrendo alla prima risponditore

Fatto e fatto.

Risposto il 21/09/2010 a 14:19
fonte dall'utente

voti
4

notifiche tastiera funzionano, ma il codice di esempio di Apple per questo presuppone che la vista di scorrimento è la vista principale della finestra. Questo di solito non è il caso. Bisogna compensare le barre di tabulazione, ecc, per ottenere il giusto offset.

E 'più facile di quanto sembri. Qui è il codice che uso in un UITableViewController. Ha due variabili di istanza, hiddenRect e keyboardShown.

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    if (keyboardShown)
        return;

    NSDictionary* info = [aNotification userInfo];

    // Get the frame of the keyboard.
    NSValue *centerValue = [info objectForKey:UIKeyboardCenterEndUserInfoKey];
    NSValue *boundsValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGPoint keyboardCenter = [centerValue CGPointValue];
    CGRect keyboardBounds = [boundsValue CGRectValue];
    CGPoint keyboardOrigin = CGPointMake(keyboardCenter.x - keyboardBounds.size.width / 2.0,
                                         keyboardCenter.y - keyboardBounds.size.height / 2.0);
    CGRect keyboardScreenFrame = { keyboardOrigin, keyboardBounds.size };


    // Resize the scroll view.
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = scrollView.frame;
    CGRect keyboardFrame = [scrollView.superview convertRect:keyboardScreenFrame fromView:nil];
    hiddenRect = CGRectIntersection(viewFrame, keyboardFrame);

    CGRect remainder, slice;
    CGRectDivide(viewFrame, &slice, &remainder, CGRectGetHeight(hiddenRect), CGRectMaxYEdge);
    scrollView.frame = remainder;

    // Scroll the active text field into view.
    CGRect textFieldRect = [/* selected cell */ frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];

    keyboardShown = YES;
}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    // Reset the height of the scroll view to its original value
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = [scrollView frame];
    scrollView.frame = CGRectUnion(viewFrame, hiddenRect);

    keyboardShown = NO;
}
Risposto il 11/07/2009 a 23:01
fonte dall'utente

voti
4

Se si utilizza un UITableView di inserire il vostro textfields ( da Jeff Lamarche ), si può semplicemente scorrere la Tableview utilizzando il metodo delegato in questo modo.

(Nota: i miei campi di testo vengono memorizzati in un array con lo stesso indice di là riga nella tableView)

- (void) textFieldDidBeginEditing:(UITextField *)textField
    {

        int index;
        for(UITextField *aField in textFields){

            if (textField == aField){
                index = [textFields indexOfObject:aField]-1;
            }
        }

         if(index >= 0) 
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

        [super textFieldDidBeginEditing:textField];
    }
Risposto il 01/05/2009 a 07:09
fonte dall'utente

voti
3

Una soluzione più snella. Si scivola nei metodi delegato UITextField, quindi non richiede pasticciano w / notifiche UIKeyboard.

Note applicative:

kSettingsRowHeight - l'altezza di un UITableViewCell.

offsetTarget e offsetThreshold sono baed off di kSettingsRowHeight. Se si utilizza una diversa altezza della riga, impostare i valori di proprietà y del punto. [Alt: calcolare l'offset in modo diverso fila.]

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGFloat offsetTarget    = 113.0f; // 3rd row
CGFloat offsetThreshold = 248.0f; // 6th row (i.e. 2nd-to-last row)

CGPoint point = [self.tableView convertPoint:CGPointZero fromView:textField];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
if (point.y > offsetThreshold) {
    self.tableView.frame = CGRectMake(0.0f,
                      offsetTarget - point.y + kSettingsRowHeight,
                      frame.size.width,
                      frame.size.height);
} else if (point.y > offsetTarget) {
    self.tableView.frame = CGRectMake(0.0f,
                      offsetTarget - point.y,
                      frame.size.width,
                      frame.size.height);
} else {
    self.tableView.frame = CGRectMake(0.0f,
                      0.0f,
                      frame.size.width,
                      frame.size.height);
}

[UIView commitAnimations];

return YES;

}

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

[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
self.tableView.frame = CGRectMake(0.0f,
                  0.0f,
                  frame.size.width,
                  frame.size.height);

[UIView commitAnimations];

return YES;

}

Risposto il 04/08/2009 a 08:18
fonte dall'utente

voti
3

Mi sono imbattuto in qualcosa di simile il vostro problema (volevo una schermata simile a settings.app di iPhone con un gruppo di celle modificabili impilati su sopra l'altro) e ha scoperto che questo approccio ha funzionato bene:

uitextfields scivolare evitare

Risposto il 27/02/2009 a 15:17
fonte dall'utente

voti
2

Un esempio in Swift, utilizzando il punto esatto del campo di testo da Get indexPath di UITextField in UITableViewCell con Swift :

func textFieldDidBeginEditing(textField: UITextField) {
    let pointInTable = textField.convertPoint(textField.bounds.origin, toView: self.accountsTableView)
    let textFieldIndexPath = self.accountsTableView.indexPathForRowAtPoint(pointInTable)
    accountsTableView.scrollToRowAtIndexPath(textFieldIndexPath!, atScrollPosition: .Top, animated: true)
}
Risposto il 21/05/2015 a 06:34
fonte dall'utente

voti
2

Molto interessante discussione, ho anche affrontato lo stesso problema potrebbe essere peggiore, perché

  1. Io sto usando un cellulare personalizzato e il campo di testo che ero dentro.
  2. Ho dovuto usare UIViewController per soddisfare le mie esigenze, quindi non posso approfittare di UITableViewController.
  3. Ho avuto criteri di filtro / ordinamento nella mia cella di una tabella, vale a dire le cellule ur continua a cambiare e tenere traccia del indexpath e tutto non sarà di aiuto.

In modo di leggere i thread qui e realizzato la mia versione, che mi ha aiutato a spingere i miei contenuti in iPad in paesaggio modalità. Ecco il codice (questo non è infallibile e tutto, ma il mio problema risolto) Prima u bisogno di avere un delegato nella classe di cella personalizzato, che sulla modifica inizia, invia il campo di testo per ur viewcontroller e impostare l'activefield = theTextField lì

// implementata per gestire PAESAGGIO SOLO MODALITÀ

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect aRect = myTable.frame;

    CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);

    aRect.size.height -= kbSize.height+50;
// This will the exact rect in which your textfield is present
        CGRect rect =  [myTable convertRect:activeField.bounds fromView:activeField];
// Scroll up only if required
    if (!CGRectContainsPoint(aRect, rect.origin) ) {


            [myTable setContentOffset:CGPointMake(0.0, rect.origin.y) animated:YES];

    }


}

// Chiamato quando l'UIKeyboardWillHideNotification viene inviato

- (void)keyboardWillHide:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    myTable.contentInset = contentInsets;
    myTable.scrollIndicatorInsets = contentInsets;
    NSDictionary* info = [aNotification userInfo];
    CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);
    CGRect bkgndRect = activeField.superview.frame;
    bkgndRect.size.height += kbSize.height;
    [activeField.superview setFrame:bkgndRect];
    [myTable setContentOffset:CGPointMake(0.0, 10.0) animated:YES];
}

-anoop4real

Risposto il 17/07/2012 a 18:11
fonte dall'utente

voti
2

Questo soluton funziona per me, si prega di notare la linea

[tableView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height+160) animated:YES];

È possibile modificare il valore 160 per abbinarlo lavorare con voi

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = activeField.superview.frame;
                        bkgndRect.size.height += kbSize.height;
     [activeField.superview setFrame:bkgndRect];
     [tableView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height+160) animated:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
   activeField = textField;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
 {
     activeField = nil;
 }
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    tableView.contentInset = contentInsets;
    tableView.scrollIndicatorInsets = contentInsets;
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = activeField.superview.frame;
    //bkgndRect.size.height += kbSize.height;
    [activeField.superview setFrame:bkgndRect];
    [tableView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height) animated:YES];
}
Risposto il 02/12/2011 a 19:28
fonte dall'utente

voti
2

Dal momento che si dispone di campi di testo in una tabella, il modo migliore è davvero per ridimensionare la tabella - è necessario impostare la tableView.frame ad essere più piccoli in altezza dalle dimensioni della tastiera (credo circa 165 pixel) e quindi espandere di nuovo quando la tastiera è respinto.

Opzionalmente si può anche interazione con l'utente disabilita per il tableView in quel momento, così, se non si desidera che l'utente lo scorrimento.

Risposto il 28/02/2009 a 19:37
fonte dall'utente

voti
1

Piccola variazione Swift 4.2 ...

Sul mio UITableView ho avuto molte sezioni ma ho dovuto evitare l'effetto intestazione galleggiante così ho usato un " dummyViewHeight approccio" come si è visto da qualche altra parte qui su Stack Overflow ... Quindi questa è la mia soluzione per questo problema (che funziona anche per la tastiera + suggerimenti barra degli strumenti +):

Dichiareremo come costante di classe:

let dummyViewHeight: CGFloat = 40.0

Poi

override func viewDidLoad() {
    super.viewDidLoad()
    //... some stuff here, not needed for this example

    // Create non floating header
    tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: dummyViewHeight))
    tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)

    addObservers()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    removeObservers()
}

E qui tutta la magia ...

@objc func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        let keyboardHeight = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
        tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: keyboardHeight, right: 0)
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.25) {
        self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.dummyViewHeight))
        self.tableView.contentInset = UIEdgeInsets(top: -self.dummyViewHeight, left: 0, bottom: 0, right: 0)
    }
}
Risposto il 08/10/2018 a 10:45
fonte dall'utente

voti
1

in viewDidLoad

-(void)viewdidload{

[super viewdidload];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

    -(void)keyboardWillChange:(NSNotification*)sender{

        NSLog(@"keyboardwillchange sender %@",sender);

float margin=0  // set your own topmargin


        CGFloat originY = [[sender.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;


        if (originY >= self.view.frame.size.height){

            NSLog(@"keyboardclose");



            [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, self.view.frame.size.height-margin)];

        }else{

            NSLog(@"keyobard on");

            float adjustedHeight = self.view.frame.size.height - margin - (self.view.frame.size.height-originY);

            [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, adjustedHeight)];
        }







    }
Risposto il 12/02/2016 a 09:14
fonte dall'utente

voti
1

Sto usando questi e funzionano come un fascino:

BSKeyboardControls - BSKeyboardControls github

TPKeyboardAvoiding - TPKeyboardAvoiding github

Risposto il 13/02/2014 a 09:30
fonte dall'utente

voti
1

Io uso questo spesso nei miei progetti. Questa soluzione funziona con scrollviews, tableviews o collectionviews ed è facile da installare. Inoltre aggancia automaticamente pulsanti su “Avanti” sulla tastiera per passare attraverso i campi di testo.

Controllare qui

Risposto il 12/02/2014 a 21:27
fonte dall'utente

voti
1

Getterò la mia soluzione (O QuickDialog di che è) nel cappello. Fondamentalmente aspettare per animare al scorrimento. Sarebbe bello avere il JIT animazione tastiera anziché il numero magico.

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.emailTextField) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 50 * USEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        });
    }
}
Risposto il 28/01/2014 a 19:05
fonte dall'utente

voti
1

soluzione facile e veloce.

Ho appena scorrere fino alla cella di destra ogni volta che lo scorrimento avviene

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView 

Supponendo So tavolo ora è in questa modalità "_keepMyCellOnTop" & So cella selezionata "_selectedCellIndex" o scorrere fino alla cella selezionata

- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{

    if (_keepMyCellOnTop)
    {
        [self.tableView scrollToRowAtIndexPath:_selectedCellIndex atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

Questo consentirà di evitare lo scorrimento.

Posizionamento del codice -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView comporterà una pergamena su e giù

Risposto il 31/12/2013 a 13:37
fonte dall'utente

voti
1

Ho appena risolto un problema da solo dopo mi sono riferito una massa di soluzioni trovate tramite Google e Stack Overflow.

In primo luogo, prego di assicurare che si è impostato un IBOutlet del vostro UIScrollView, quindi si prega di dare un'occhiata da vicino di Apple Doc: Gestione della tastiera . Infine, se è possibile scorrere lo sfondo, ma la tastiera copre ancora il campi di testo, si prega di dare un'occhiata a questo pezzo di codice:

// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;

if (aRect.size.height < activeField.frame.origin.y+activeField.frame.size.height) {

    CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y+activeField.frame.size.height-aRect.size.height);

    [scrollView setContentOffset:scrollPoint animated:YES];

La principale differenza tra questo pezzo e la menzogna di Apple nel caso condizione. Credo che il calcolo di Apple della distanza di scorrimento e la condizione del campo di testo se coperto da tastiera non sono accurate, così ho fatto la mia modifica come sopra.

Fatemi sapere se funziona

Risposto il 18/08/2012 a 11:10
fonte dall'utente

voti
1

Ecco come ho fatto questo lavoro, che è una miscela di Sam Ho e le risposte di Marcel W, e alcuni dei miei bug fix rilasciati al mio codice scadente. Io sto usando un UITableViewController. Il tavolo ora ridimensiona correttamente quando viene visualizzata la tastiera.

1) In viewDidLoadho aggiunto:

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

2) mi ero dimenticato di chiamare le superequivalenti in viewWillAppeare awakeFromNib. Ho aggiunto questi indietro in.

Risposto il 26/07/2012 a 18:18
fonte dall'utente

voti
1

Se l'UITableView è gestito da una sottoclasse di UITableViewController e non UITableView, e il delegato campo di testo è l'UITableViewController, si dovrebbe gestire tutto lo scorrimento automatico - tutte queste altre osservazioni sono molto difficile da attuare nella pratica.

Per un buon esempio vedere il progetto di esempio di codice mela: TaggedLocations.

Si può vedere che scorre automaticamente, ma non sembra essere qualsiasi codice che fa questo. Questo progetto ha anche vista celle della tabella personalizzato, quindi se si genera l'applicazione con esso come una guida, si dovrebbe ottenere il risultato desiderato.

Risposto il 05/03/2012 a 07:09
fonte dall'utente

voti
1

Un altro metodo semplice (funziona solo con una sezione)

//cellForRowAtIndexPath
UItextField *tf;
[cell addSubview:tf];
tf.tag = indexPath.row;
tf.delegate = self;

//textFieldDidBeginEditing:(UITextField *)text
[[self.tableView scrollToRowsAtIndexPath:[NSIndexPath indexPathForRow:text.tag in section:SECTIONINTEGER] animated:YES];
Risposto il 23/11/2011 a 17:25
fonte dall'utente

voti
1

Così, dopo ore di lavoro estenuante cercando di utilizzare queste soluzioni attuali (e assolutamente non) ho finalmente ottenuto le cose che lavorano bene, e li aggiornato per utilizzare i nuovi blocchi di animazione. La mia risposta è interamente basato su risposta di Ortwin sopra .

Quindi per qualsiasi motivo il codice di cui sopra è stata solo non funziona per me. La mia configurazione sembrava abbastanza simile agli altri, ma forse perché ero su un iPad o 4.3 ... idea. Si stava facendo un po 'di matematica stravagante e tiro la mia Tableview fuori dallo schermo.

Vedi risultato finale della mia soluzione: http://screencast.com/t/hjBCuRrPC (Si prega di ignorare la foto :-P).

Così sono andato con il succo di quello che stava facendo Ortwin, ma cambiato come si stava facendo un po 'di matematica per aggiungere l'origin.y & size.height della mia vista tabella con l'altezza della tastiera. Quando mi sottraggo l'altezza della finestra da questo risultato, mi dice quanto intersezione ho in corso. Se maggiore di 0 (cioè v'è una certa sovrapposizione) effettuo l'animazione della altezza del telaio.

In aggiunta ci sono stati alcuni problemi di aggiornamento che sono stati risolti con 1) in attesa di scorrere alla cella fino a quando l'animazione è stata fatta e 2) utilizzando l'opzione UIViewAnimationOptionBeginFromCurrentState quando nasconde la tastiera.

Un paio di cose da notare.

  • _topmostRowBeforeKeyboardWasShown & _originalFrame sono variabili di istanza dichiarate nell'intestazione.
  • self.guestEntryTableView è la mia tableView (io sono in un file esterno)
  • IASKCGRectSwap è il metodo di Ortwin per sfogliare le coordinate di un telaio
  • Aggiorno solo l'altezza del tableView se almeno 50px di esso sta per essere mostra
  • Dal momento che non sono in un UIViewController non ho self.view, quindi ho solo tornare il tableView alla sua cornice originale

Anche in questo caso, non avrei ottenuto nelle vicinanze di questa risposta se io Ortwin non ha fornito il punto cruciale di esso. Ecco il codice:

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.activeTextField = textField;

    if ([self.guestEntryTableView indexPathsForVisibleRows].count) {
        _topmostRowBeforeKeyboardWasShown = (NSIndexPath*)[[self.guestEntryTableView indexPathsForVisibleRows] objectAtIndex:0];
    } else {
        // this should never happen
        _topmostRowBeforeKeyboardWasShown = [NSIndexPath indexPathForRow:0 inSection:0];
        [textField resignFirstResponder];
    }
}

- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.activeTextField = nil;
}

- (void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary* userInfo = [notification userInfo];

    NSValue* keyboardFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    // Reduce the tableView height by the part of the keyboard that actually covers the tableView
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
    CGRect viewRectAbsolute = [self.guestEntryTableView convertRect:self.guestEntryTableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
    CGRect keyboardFrame = [keyboardFrameValue CGRectValue];
    if (UIInterfaceOrientationLandscapeLeft == orientation ||UIInterfaceOrientationLandscapeRight == orientation ) {
        windowRect = IASKCGRectSwap(windowRect);
        viewRectAbsolute = IASKCGRectSwap(viewRectAbsolute);
        keyboardFrame = IASKCGRectSwap(keyboardFrame);
    }

    // fix the coordinates of our rect to have a top left origin 0,0
    viewRectAbsolute = FixOriginRotation(viewRectAbsolute, orientation, windowRect.size.width, windowRect.size.height);

    CGRect frame = self.guestEntryTableView.frame;
    _originalFrame = self.guestEntryTableView.frame;

    int remainder = (viewRectAbsolute.origin.y + viewRectAbsolute.size.height + keyboardFrame.size.height) - windowRect.size.height;

    if (remainder > 0 && !(remainder > frame.size.height + 50)) {
        frame.size.height = frame.size.height - remainder;
        float duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration: duration
                        animations:^{
                            self.guestEntryTableView.frame = frame;
                        }
                        completion:^(BOOL finished){
                            UITableViewCell *textFieldCell = (UITableViewCell*) [[self.activeTextField superview] superview];
                            NSIndexPath *textFieldIndexPath = [self.guestEntryTableView indexPathForCell:textFieldCell];
                            [self.guestEntryTableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                        }];
    }

}

- (void)keyboardWillHide:(NSNotification*)notification {
    NSDictionary* userInfo = [notification userInfo];
    float duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration: duration
                          delay: 0.0
                        options: (UIViewAnimationOptionBeginFromCurrentState)
                     animations:^{
                         self.guestEntryTableView.frame = _originalFrame;
                     }
                     completion:^(BOOL finished){
                         [self.guestEntryTableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
                     }];

}   

#pragma mark CGRect Utility function
CGRect IASKCGRectSwap(CGRect rect) {
    CGRect newRect;
    newRect.origin.x = rect.origin.y;
    newRect.origin.y = rect.origin.x;
    newRect.size.width = rect.size.height;
    newRect.size.height = rect.size.width;
    return newRect;
}

CGRect FixOriginRotation(CGRect rect, UIInterfaceOrientation orientation, int parentWidth, int parentHeight) {
    CGRect newRect;
    switch(orientation)
    {
        case UIInterfaceOrientationLandscapeLeft:
            newRect = CGRectMake(parentWidth - (rect.size.width + rect.origin.x), rect.origin.y, rect.size.width, rect.size.height);
            break;
        case UIInterfaceOrientationLandscapeRight:
            newRect = CGRectMake(rect.origin.x, parentHeight - (rect.size.height + rect.origin.y), rect.size.width, rect.size.height);
            break;
        case UIInterfaceOrientationPortrait:
            newRect = rect;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            newRect = CGRectMake(parentWidth - (rect.size.width + rect.origin.x), parentHeight - (rect.size.height + rect.origin.y), rect.size.width, rect.size.height);
            break;
    }
    return newRect;
}
Risposto il 18/07/2011 a 09:45
fonte dall'utente

voti
1

Ho provato quasi lo stesso approccio e si avvicinò con un codice più semplice e più piccolo per la stessa. Ho creato un IBOutlet iTextView e associati con l'UITextView nella IB.

 -(void)keyboardWillShow:(NSNotification *)notification
    {
        NSLog(@"Keyboard");
        CGRect keyFrame = [[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

        [UIView beginAnimations:@"resize view" context:nil];
        [UIView setAnimationCurve:1];
        [UIView setAnimationDuration:1.0];
        CGRect frame = iTableView.frame;
        frame.size.height = frame.size.height -  keyFrame.size.height;
        iTableView.frame = frame;
        [iTableView scrollRectToVisible:frame animated:YES];
        [UIView commitAnimations];

    }
Risposto il 13/05/2011 a 06:00
fonte dall'utente

voti
1

Questo funziona perfettamente, e su iPad troppo.

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

    if(textField == textfield1){
            [accountName1TextField becomeFirstResponder];
        }else if(textField == textfield2){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield3 becomeFirstResponder];

        }else if(textField == textfield3){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield4 becomeFirstResponder];

        }else if(textField == textfield4){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield5 becomeFirstResponder];

        }else if(textField == textfield5){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield6 becomeFirstResponder];

        }else if(textField == textfield6){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield7 becomeFirstResponder];

        }else if(textField == textfield7){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield8 becomeFirstResponder];

        }else if(textField == textfield8){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield9 becomeFirstResponder];

        }else if(textField == textfield9){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textField resignFirstResponder];
        }
Risposto il 23/10/2010 a 08:11
fonte dall'utente

voti
0

Ho appena scoperto un altro bug quando si utilizza UITableViewController. Non era scorre automaticamente quando la tastiera si presentò. Ho notato che è stato a causa di contentInsetAdjustmentBehavior = .Never su UITableView.

Risposto il 03/07/2019 a 21:30
fonte dall'utente

voti
0

Soluzione per Swift 3-4 con animazioni e tastiera cornice cambia:

In primo luogo, creare un Bool:

// MARK: - Private Properties
private var isKeyboardShowing = false

In secondo luogo, aggiungere osservatori alle notifiche tastiera del sistema:

// MARK: - Overriding ViewController Life Cycle Methods
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: .UIKeyboardWillChangeFrame, object: nil)
}

In terzo luogo, preparare la funzione di animazione:

func adjustTableViewInsets(keyboardHeight: CGFloat, duration: NSNumber, curve: NSNumber){
    var extraHeight: CGFloat = 0
    if keyboardHeight > 0 {
        extraHeight = 20
        isKeyboardShowing = true
    } else {
        isKeyboardShowing = false
    }

    let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight + extraHeight, right: 0)
    func animateFunc() {
        //refresh constraints
        //self.view.layoutSubviews()
        tableView.contentInset = contentInset
    }

    UIView.animate(withDuration: TimeInterval(duration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(curve))], animations: animateFunc, completion: nil)
}

Quindi aggiungere i metodi target / azione (chiamato dagli osservatori):

// MARK: - Target/Selector Actions
func keyboardWillShow(notification: NSNotification) {
    if !isKeyboardShowing {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height

            let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
            let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
    let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
    adjustTableViewInsets(keyboardHeight: 0, duration: duration, curve: curve)
}

func keyboardWillChangeFrame(notification: NSNotification) {
    if isKeyboardShowing {
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

        if let newKeyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = newKeyboardSize.height
            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

Infine, non dimenticare di rimuovere gli osservatori in deinit o in viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}
Risposto il 10/06/2018 a 15:48
fonte dall'utente

voti
0

Non necessita di nessuna calcoli, l'uso di sotto del codice funzionerà: Questo codice che ho usato nel mio personalizzato UITableViewCell, sta funzionando:

override func viewDidLoad() {
super.viewDidLoad()

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)}


func keyboardWillShow(_ notification:Notification) {

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
    tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
}}


func keyboardWillHide(_ notification:Notification) {

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}}
Risposto il 22/02/2018 a 07:47
fonte dall'utente

voti
0

Swift 4 soluzione completa:

  • Correttamente lavora con tastiera cambiamenti telaio (ad esempio altezza della tastiera cambia come emojii → tastiera normale).
  • Supporto TabBar & Toolbar per UITableView esempio (in altri esempi si riceve inserti errate).
  • Durata animazione dinamica (non hard-coded).
  • Protocollo-oriented, in modo da poter facilmente utilizzare in qualsiasi situazione.
  • Inserti di scorrimento funziona troppo.

Ho scritto il protocollo aiutante (è possibile scaricarlo come succo , perché è troppo grande per scrivere un commento sul StackOverflow), quindi la visualizzazione solo bisogno di:

  1. Adotta KeyboardChangeFrameObserveril protocollo:

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions)
    
  2. Chiamata observeKeyboardFrameChanges()sul apparire.

esempio di implementazione di tale protocollo per tableView:

class TestViewController: UITableViewController, KeyboardChangeFrameObserver {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        observeKeyboardFrameChanges()
    }

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions) {
        var adjustedHeight = height

        if let tabBarHeight = self.tabBarController?.tabBar.frame.height {
            adjustedHeight -= tabBarHeight
        } else if let toolbarHeight = navigationController?.toolbar.frame.height, navigationController?.isToolbarHidden == false {
            adjustedHeight -= toolbarHeight
        }

        if adjustedHeight < 0 { adjustedHeight = 0 }

        UIView.animate(withDuration: animationDuration, animations: {
            let newInsets = UIEdgeInsets(top: 0, left: 0, bottom: adjustedHeight, right: 0)
            self.tableView.contentInset = newInsets
            self.tableView.scrollIndicatorInsets = newInsets
        })
    }

}
Risposto il 12/01/2018 a 00:10
fonte dall'utente

voti
0
// scroll tableview so content ends at the middle of the tableview (out of the way of the keyboard)
CGPoint newContentOffset = CGPointMake(0, [self.tableView contentSize].height - (self.tableView.bounds.size.height / 2));
[self.tableView setContentOffset:newContentOffset animated:YES];
Risposto il 27/06/2017 a 21:12
fonte dall'utente

voti
0

Guardate la mia versione :)

    - (void)keyboardWasShown:(NSNotification *)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = cellSelected.superview.frame;
    bkgndRect.size.height += kbSize.height;
    [cellSelected.superview setFrame:bkgndRect];
    [tableView setContentOffset:CGPointMake(0.0, cellSelected.frame.origin.y-kbSize.height) animated:YES];
}


- (void)keyboardWasHidden:(NSNotification *)aNotification
{
    [tableView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
Risposto il 02/07/2016 a 20:32
fonte dall'utente

voti
0

Ecco la mia soluzione ispirata schermata "Event Edit" dal iOS7 Calendario app.

Uno dei punti chiave di questa soluzione è che la tastiera è respinto quando la tabella utente scorre.

Implementazione:

1) Aggiungere proprietà che memorizzerà campo di testo selezionato:

@property (strong) UITextField *currentTextField;

e variabili BOOL che useremo per controllare se abbiamo bisogno di nascondere la tastiera quando la tabella utente scorre.

BOOL hideKeyboardOnScroll;

2) Maniglia UITextField callback delegato:

#pragma mark - UITextFieldDelegate

- (void) textFieldDidBeginEditing: (UITextField *) textField {
    self.currentTextField = textField;
}

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

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

    CGPoint newContentOffset = CGPointZero;
    if (tableView.contentSize.height > tableView.frame.size.height) {
        newContentOffset.y = MIN(tableView.contentOffset.y, tableView.contentSize.height - tableView.frame.size.height);
    }
    [tableView setContentOffset: newContentOffset animated: YES];

    return YES;
}

3) Maniglia metodo UIScrollViewDelegate per controllare che vista utente scorrimento.

#pragma mark - UIScrollViewDelegate

- (void) scrollViewDidScroll: (UIScrollView *) scrollView {
    if (hideKeyboardOnScroll == YES) {
        [self.currentTextField resignFirstResponder];
    }
}

4) Iscriviti alle notifiche della tastiera nel metodo di viewcontroller [viewWillAppear] e annullare la sottoscrizione in [viewWillDisappear] metodo.

- (void) viewWillAppear: (BOOL) animated {
    [super viewWillAppear: animated];

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

- (void) viewWillDisappear: (BOOL) animated {
    [super viewWillDisappear: animated];

    [ [NSNotificationCenter defaultCenter] removeObserver: self name: UIKeyboardDidShowNotification object: nil];
    [ [NSNotificationCenter defaultCenter] removeObserver: self name: UIKeyboardWillHideNotification object: nil];    
}

5) Maniglia notifiche della tastiera:

- (void) keyboardWillShow: (NSNotification *) notification {
    CGRect keyboardFrame = [ [ [notification userInfo] objectForKey: UIKeyboardFrameBeginUserInfoKey] CGRectValue];

    // Find cell with textfield.
    CGRect textFieldFrame = [tableView convertRect: self.currentTextField.frame fromView: self.currentTextField];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint: textFieldFrame.origin];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
    //

    // Shrink tableView size.
    CGRect tableViewFrame = tableView.frame;
    tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width,
                             self.view.frame.size.height - tableView.frame.origin.y - keyboardFrame.size.height);
    //

    // Check if cell is visible in shrinked table size.
    BOOL cellIsFullyVisible = YES;
    if ( cell.frame.origin.y < tableView.contentOffset.y ||
        (cell.frame.origin.y + cell.frame.size.height) > (tableView.contentOffset.y + tableView.frame.size.height) ) {
        cellIsFullyVisible = NO;
    }
    //

    // If cell is not fully visible when scroll table to show cell;
    if (cellIsFullyVisible == NO) {
        CGPoint contentOffset = CGPointMake(tableView.contentOffset.x, CGRectGetMaxY(cell.frame) - tableView.frame.size.height);
        if (cell.frame.origin.y < tableView.contentOffset.y) {
            contentOffset.y = cell.frame.origin.y;
        }
        contentOffset.y = MAX(0, contentOffset.y);

        // For some reason [setContentOffset] is called without delay then
        // this code may not work for some cells. That why we call it with brief delay.
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [UIView animateWithDuration: 0.5 animations:^{
                [tableView setContentOffset: contentOffset animated: NO];
            } completion: ^(BOOL finished) {
                hideKeyboardOnScroll = YES;
            }];
        });
    } else {
        hideKeyboardOnScroll = YES;
    }
    //

    // Finally restore original table frame.
    tableView.frame = tableViewFrame;
    //
}

- (void) keyboardWillHide: (NSNotification *) notification {
    [super keyboardWillHide: notification];

    hideKeyboardOnScroll = NO;
}
Risposto il 21/08/2014 a 15:43
fonte dall'utente

voti
0

Penso che il modo migliore è attraverso UITableViewController.

Se si desidera un UITableView in un UIViewController , basta fare un contentView con UITableViewController incorporato e mettere le seguenti righe nel viedDidLoad del UIViewController:

self.tableView = ((UITableViewController*)self.childViewControllers[0]).tableView;
self.tableView.delegate = self;
self.tableView.dataSource = self;

Facile;)

Risposto il 06/06/2014 a 16:29
fonte dall'utente

voti
0

Penso che ci sia alcun modo "giusto" per fare questo. Devi scegliere la migliore soluzione di misura per il vostro caso d'uso. Nel mio App iPad ho una UIViewControllerche si presenta come modali UIModalPresentationFormSheete si compone di una UITableView. Questa tabella contiene due UITextFieldsper cella. Basta chiamare scrollToRowAtIndexPath:atScrollPosition:animated:nel textFieldDidBeginEditing:metodo non funziona per me. Quindi ho creato un tableFooterView:

- (void)viewDidLoad
{
    [super viewDidLoad];

    m_footerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, m_tableView.frame.size.width, 300.0f)];
    [m_footerView setBackgroundColor:[UIColor clearColor]];
    [m_tableView setTableFooterView:m_footerView];
    [m_footerView release];
}

L'idea è che la tastiera nasconde il tableFooterViewe non UITextFields. Così il tableFooterViewdeve essere abbastanza alto. Dopo di che è possibile utilizzare scrollToRowAtIndexPath:atScrollPosition:animated:nel textFieldDidBeginEditing:metodo.

Penso che sia anche possibile mostrare e nascondere il tableFooterViewmodo dinamico con l'aggiunta di osservatori per le notifiche della tastiera ma non l'ho ancora provato:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

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

- (void)keyboardWillShow:(NSNotification *)notification 
{
     [m_tableView setTableFooterView:m_footerView];
}

- (void)keyboardWillHide:(NSNotification *)notification 
{
     [m_tableView setTableFooterView:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
Risposto il 15/09/2012 a 08:51
fonte dall'utente

voti
0

ho creato un piccolo progetto che risolve questo problema con la tastiera, nel mio caso ho solo bisogno di rendere la vista della tabella salire quando la tastiera si presenta.

Spero che questo ti aiuti!

http://git.io/BrH9eQ

Risposto il 19/11/2011 a 21:21
fonte dall'utente

voti
0

Ho appena guardato di nuovo in iOS 5.0 di riferimento lib e trovato questa sezione intitolata "Contenuto che si trova sotto la tastiera Moving": TextAndWebiPhoneOS KeyboardManagement

È questa nuova dal momento che iOS 5, forse? Non ho letto in esso ancora come io sono nel bel mezzo di qualcosa d'altro, ma forse altri saperne di più e me e gli altri può illuminare qui.

Ha il doc di Apple sostituisce ciò che è stato discusso qui o sono le informazioni qui ancora utili per gli utenti iOS 5 SDK?

Risposto il 26/10/2011 a 12:07
fonte dall'utente

voti
0

UITableViewControllerfa lo scorrimento automatico, anzi. La differenza rispetto al utilizzando una UIViewControllerè che si deve creare Navbar-Buttonitems di programmazione utilizzando il NavigationController, quando si utilizza un TableViewController.

Risposto il 20/03/2011 a 20:59
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more