Het maken van een UITableView scroll wanneer tekstveld is geselecteerd

stemmen
228

Na veel vallen en opstaan, ben ik het opgeven en het stellen van de vraag. Ik heb veel mensen met dezelfde problemen gezien, maar kan niet alle antwoorden recht op werk.

Ik heb een UITableViewdie is samengesteld uit aangepaste cellen. De cellen zijn van 5 tekstvelden naast elkaar (ongeveer zoals een rooster).

Wanneer ik probeer om te scrollen en de cellen te bewerken op de bodem van het UITableView, kan ik niet in geslaagd om mijn cellen behoorlijk boven het toetsenbord geplaatst.

Ik heb veel antwoorden te praten over het veranderen van uitzicht maten, etc gezien ... maar geen van hen is mooi nu toe gewerkt.

Kan iemand verduidelijken de juiste manier om dit te doen met een concreet code voorbeeld?

De vraag is gesteld op 27/02/2009 om 11:05
bron van user
In andere talen...                            


48 antwoorden

stemmen
110

Als je UITableViewController plaats van UIViewController gebruiken, zal het automatisch doen.

antwoordde op 21/09/2010 om 04:42
bron van user

stemmen
89

De functie die het scrollen doet kan veel eenvoudiger:

- (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];
}

Dat is het. Geen berekeningen helemaal.

antwoordde op 15/04/2009 om 13:21
bron van user

stemmen
65

Ik ben iets vergelijkbaars is het generiek te doen, geen behoefte om iets specifiek voor uw code te berekenen. Kijk maar in de toelichting op de code:

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+ versie:

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()
        }
    }
}
antwoordde op 13/04/2010 om 15:46
bron van user

stemmen
41

Ik had hetzelfde probleem, maar merkte dat het verschijnt alleen in één weergave. Dus ik begon te zoeken naar de verschillen in de controllers.

Ik kwam erachter dat het scrollen gedrag ligt in - (void)viewWillAppear:(BOOL)animatedde super-instantie.

Dus zorg ervoor dat uit te voeren als volgt uit:

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

En het maakt niet uit als je gebruik maakt UIViewControllerof UITableViewController; controleerde het door een UITableViewals een subweergave van self.view in de UIViewController. Het was hetzelfde gedrag. Het uitzicht was niet mogelijk om te scrollen als het gesprek [super viewWillAppear:animated];ontbrak.

antwoordde op 29/05/2011 om 01:42
bron van user

stemmen
37

Ik kan dit gemist hebben, als ik het hele bericht hier niet lezen, maar wat ik kwam met lijkt bedrieglijk eenvoudig. Ik heb dit niet gebracht door de wringer, het testen in alle situaties, maar het lijkt erop dat het prima zou moeten werken.

eenvoudig de contentInset van de Tableview aanpassen door de hoogte van het toetsenbord en schuif vervolgens de cel naar beneden:

- (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];
}

en uiteraard

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

is dit te simpel? mis ik iets? tot nu toe het werkt voor mij prima, maar zoals ik al zei, heb ik zet het niet door de wringer ...

antwoordde op 18/08/2012 om 01:12
bron van user

stemmen
35

De eenvoudigste oplossing voor Swift 3 , gebaseerd op Bartłomiej Semańczyk oplossing :

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)
    })
}
antwoordde op 08/12/2016 om 13:26
bron van user

stemmen
34

Als je kunt gebruiken UITableViewController, krijg je de functionaliteit gratis. Soms is dit echter geen optie, vooral als u meerdere standpunten niet alleen de behoefte UITableView.

Een aantal van de hieronder voorgestelde oplossingen niet werken op iOS ≥4, sommige werken niet op de iPad of in landscape-modus, sommige werken niet voor Bluetooth-toetsenborden (waar we willen geen scrollen), andere niet werken bij het schakelen tussen meerdere tekstvelden. Dus als u een oplossing kiest, zorg ervoor om deze zaken te testen. Dit is de oplossing die we gebruiken gebruikt 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];
    }
}   

Hier is de volledige code van de klasse in InAppSettingsKit. Om het te testen, gebruik dan de "Complete List" venster kind waar je de hierboven genoemde scenario's kunnen testen.

antwoordde op 13/12/2010 om 17:01
bron van user

stemmen
34

Ik denk dat ik ben gekomen met de oplossing om het gedrag van Apple's apps te passen.

Ten eerste, in uw viewWillAppear: abonneren op het toetsenbord meldingen, zodat u weet wanneer het toetsenbord te tonen en te verbergen, en het systeem zal u de grootte van het toetsenbord, maar niet' vergeten af ​​te melden in uw viewWillDisappear :.

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

Implementeren van de vergelijkbaar met de volgende methoden, zodat u de grootte van uw tableView aan te passen aan het zichtbare gebied dat ooit het toetsenbord shows te passen. Hier ben ik het bijhouden van de toestand van het toetsenbord afzonderlijk dus ik kan kiezen wanneer de tableView terug naar volledige hoogte te stellen mezelf, omdat je deze meldingen op elk gebied te veranderen. Vergeet niet uit te voeren keyboardWillHide: en kies ergens geschikt is voor uw tableView maat te lossen.

-(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];
    }
}

Nu hier is het scrollen bit, we werken aan een paar maten eerst, dan zien we waar we zijn in het zichtbare gebied, en stel de rect we willen om naar ofwel de helft uitzicht boven of onder het midden van het veld op tekst gebaseerd zijn van waar het in de weergave. In dit geval hebben we een reeks UITextFields en een enumeratie dat spoor daarvan houdt, zodat de vermenigvuldiging rowHeight het rijnummer geeft ons de actuele verschuiving van het frame in het buitenaanzicht.

- (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];
}

Dit lijkt heel mooi werk.

antwoordde op 23/03/2009 om 02:49
bron van user

stemmen
22

De eenvoudigste oplossing voor 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
    }
antwoordde op 25/08/2015 om 06:42
bron van user

stemmen
6

Ik hoop dat jullie al een oplossing te lezen van al die kreeg. Maar ik vond mijn oplossing als volgt. Ik verwacht dat je al een cel met UITextField. Dus over het voorbereiden gewoon blijven de rij-index in tag van het tekstveld.

cell.textField.tag = IndexPath.row;

Maak een activeTextField, voorbeeld van UITextFieldmet globaal bereik, zoals hieronder:

@interface EditViewController (){

    UITextField *activeTextField;

}

Zo, nu heb je gewoon kopiëren plakken mijn code aan het eind. En vergeet ook niet om toe te voegenUITextFieldDelegate

#pragma mark - TextField Delegation

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

    activeTextField = textField;

    return YES;
}

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

    activeTextField = nil;

}

registers toetsenbord 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];



}

Handvatten Keyboard Notifications:

Aangeroepen wanneer het UIKeyboardDidShowNotificationwordt verzonden.

- (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];

}

Aangeroepen wanneer het UIKeyboardWillHideNotificationwordt verzonden

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

}

Nu is een ding blijft: Roep de registerForKeyboardNotificationsmethode in om ViewDidLoadmethode als volgt:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Registering keyboard notification

    [self registerForKeyboardNotifications];

    // Your codes here...

}

Je bent klaar, hoop dat je textFieldsniet langer verborgen door het toetsenbord.

antwoordde op 03/01/2015 om 21:36
bron van user

stemmen
6

Het combineren en invuloefeningen uit meerdere antwoorden (met name Ortwin Gentz, user 98.013) en andere post Dit werkt uit de doos voor SDK 4.3 op een iPad in de staande of liggende modus:

@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
antwoordde op 03/08/2011 om 03:35
bron van user

stemmen
5

Mijn aanpak:

Ik voor het eerst subklasse UITextField en voeg een indexPath eigendom. In de cellFor ... methode die ik overhandigen het pand indexPath.

Daarna heb ik volgende code toe te voegen:

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);}];

aan de textFieldShould / WillBegin ... etc.

Wanneer het toetsenbord verdwijnt je moet het tij te keren met:

[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, 0);}];
antwoordde op 29/09/2012 om 13:03
bron van user

stemmen
4

Gebruik UITextField's delegatemethode:

Snel

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
}

Doelstelling 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;
}
antwoordde op 20/03/2015 om 07:00
bron van user

stemmen
4

Het juiste antwoord is het antwoord van Sam Ho's:

"Als je UITableViewController plaats van UIViewController te gebruiken, zal het automatisch doen.".

Zorg ervoor dat u uw UITableView te verbinden met de eigenschap TableView van de UITableViewController (dus bijvoorbeeld het niet toe te voegen als een subweergave van de Woning bekijken van de UITableViewController).

Zorg er ook voor om de woning AutoresizingMask van uw UITableView ingesteld op FlexibleHeight

antwoordde op 09/12/2010 om 11:28
bron van user

stemmen
4

Als u Three20, dan gebruik maken van de autoresizesForKeyboardwoning. Stel gewoon in het uw weergave controller -initWithNibName:bundlemethode

self.autoresizesForKeyboard = YES

Dit zorgt voor:

  1. Luisteren keyboard kennisgevingen en verstelraam tabelweergave is
  2. Scrollen naar de first responder

Klaar en klaar.

antwoordde op 21/09/2010 om 14:19
bron van user

stemmen
4

Toetsenbord meldingen werken, maar Apple's sample code voor dat veronderstelt dat de scroll uitzicht is de wortel uitzicht van het venster. Dit is meestal niet het geval. Je moet compenseren voor het tabblad bars, enz., Om de juiste compensatie te krijgen.

Het is makkelijker dan het klinkt. Hier is de code die ik gebruik in een UITableViewController. Het heeft twee instantievariabelen, hiddenRect en 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;
}
antwoordde op 11/07/2009 om 23:01
bron van user

stemmen
4

Als je een UITableView gebruiken om uw tekstvelden te plaatsen ( van Jeff Lamarche ), kunt u gewoon scrollen de Tableview met behulp van de afgevaardigde methode zoals zo.

(Let op: mijn tekst velden worden opgeslagen in een array met dezelfde index als er in de Tableview rij)

- (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];
    }
antwoordde op 01/05/2009 om 07:09
bron van user

stemmen
3

Een gestroomlijnde oplossing. Hij glijdt in de UITextField gemachtigde methoden, zodat het niet nodig knoeien w / UIKeyboard meldingen.

Implementatie notes:

kSettingsRowHeight - de hoogte van een UITableViewCell.

offsetTarget en offsetThreshold zijn baed off van kSettingsRowHeight. Als u een andere rijhoogte gebruiken, stelt deze waarden op eigenschap y punt's. [Alt: bereken de rij versprongen op een andere manier.]

- (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;

}

antwoordde op 04/08/2009 om 08:18
bron van user

stemmen
3

Ik kwam iets als uw probleem (ik wilde een scherm dat lijkt op de iPhone settings.app met een bos van bewerkbare cellen gestapeld op de top van een ander) en vond dat deze aanpak goed gewerkt:

schuiven UITextFields rond te vermijden

antwoordde op 27/02/2009 om 15:17
bron van user

stemmen
2

Een voorbeeld in Swift, met behulp van de exacte punt van het tekstveld van Get indexPath van UITextField in UITableViewCell met 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)
}
antwoordde op 21/05/2015 om 06:34
bron van user

stemmen
2

Zeer interessante discussie thread, ik ook geconfronteerd met het zelfde probleem kan erger een omdat zijn

  1. Ik was met behulp van een aangepaste cel en het tekstveld binnen was dat.
  2. Ik moest UIViewController gebruiken om mijn eisen te voldoen, dus kan profiteren van UITableViewController.
  3. Ik had filter / sort criteria in mijn tafel cel, dat wil zeggen ur cellen blijft veranderen en het bijhouden van de indexPath en al zal niet helpen.

Dus lees de draden hier en mijn versie, die me geholpen in omhoog te duwen mijn inhoud in iPad in geïmplementeerd landscape -modus. Hier is de code (dit is niet fool proof en al, maar het vaste mijn probleem) Eerste u moet een afgevaardigde in uw aangepaste mobiele klasse, die over het bewerken begint, verzendt het tekstveld om ur ViewController en zet de activefield = theTextField er

// geïmplementeerd om alleen omgaan met landscape-modus

- (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];

    }


}

// aangeroepen wanneer de UIKeyboardWillHideNotification wordt gestuurd

- (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

antwoordde op 17/07/2012 om 18:11
bron van user

stemmen
2

Dit soluton werkt voor mij, let dan op de lijn

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

U kunt de 160 waarde te wijzigen om te matchen met u

- (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];
}
antwoordde op 02/12/2011 om 19:28
bron van user

stemmen
2

Aangezien u tekstvelden in een tafel, de beste manier is echt om de tafel formaat wijzigen - u nodig hebt om de tableView.frame opnieuw ingesteld om kleiner te hoog zijn door de grootte van het toetsenbord (ik denk dat ongeveer 165 pixels) en vervolgens uit te breiden wanneer het toetsenbord wordt afgewezen.

U kunt desgewenst ook uitschakelen interactie met de gebruiker voor de tableView op dat moment zo goed, als je niet wilt dat de gebruiker scrollen.

antwoordde op 28/02/2009 om 19:37
bron van user

stemmen
1

Kleine variatie met Swift 4.2 ...

Op mijn UITableView had ik zoveel secties maar ik moest de drijvende header effect te vermijden , dus ik gebruik gemaakt van een " dummyViewHeight " aanpak zoals ergens anders gezien hier op Stack Overflow ... Dus dit is mijn oplossing voor dit probleem (het werkt ook voor keyboard + toolbar + suggesties):

Verklaren als klasse constant:

let dummyViewHeight: CGFloat = 40.0

Dan

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()
}

En hier alle magie ...

@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)
    }
}
antwoordde op 08/10/2018 om 10:45
bron van user

stemmen
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)];
        }







    }
antwoordde op 12/02/2016 om 09:14
bron van user

stemmen
1

Ik gebruik deze en ze werken als een charme:

BSKeyboardControls - BSKeyboardControls github

TPKeyboardAvoiding - TPKeyboardAvoiding github

antwoordde op 13/02/2014 om 09:30
bron van user

stemmen
1

Ik gebruik dit vaak in mijn projecten. Deze oplossing werkt met scrollviews, tableviews of collectionviews en het is gemakkelijk te installeren. Het haakt ook automatisch up “Next” knoppen op het toetsenbord door de tekst velden te schakelen.

Check it hier

antwoordde op 12/02/2014 om 21:27
bron van user

stemmen
1

Ik zal mijn oplossing (Of ​​QuickDialog dat is) in de hoed te gooien. In principe wachten om te animeren naar het scrollen. Het zou leuk zijn om het toetsenbord animatie JIT in plaats van het magische getal te krijgen.

-(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];
        });
    }
}
antwoordde op 28/01/2014 om 19:05
bron van user

stemmen
1

Eenvoudige en snelle oplossing.

Ik ga naar de juiste cel wanneer scrollen gebeurt

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView 

Ervan uitgaande dat ik weet tafel nu in deze modus "_keepMyCellOnTop" & Ik weet geselecteerde cel "_selectedCellIndex" of blader naar geselecteerde cel

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

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

Dit zal scrollen te voorkomen.

Het plaatsen van de code in -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView een scroll resultaat op en neer

antwoordde op 31/12/2013 om 13:37
bron van user

stemmen
1

Ik heb net zo'n probleem opgelost door mij nadat ik een massa van oplossingen gevonden via Google en stack overflow bedoeld.

Ten eerste, dan kunt u ervoor zorgen dat u hebt het opzetten van een IBOutlet van uw UIScrollView, dan neem een goede blik op Apple Doc: Keyboard management . Tenslotte, als je de achtergrond kunt bladeren, maar het toetsenbord dekt nog steeds de tekstvelden, neem dan eens een kijkje op dit stuk van code:

// 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];

Het belangrijkste verschil tussen dit stuk en leugens van Apple in de if conditie. Ik denk dat Apple's berekening van de scroll-afstand en de staat van de vraag of het tekstveld onder het toetsenbord zijn niet nauwkeurig, dus ik maakte mijn modificatie als hierboven.

Laat me weten of het werkt

antwoordde op 18/08/2012 om 11:10
bron van user

stemmen
1

Hier is hoe ik dit werk, dat is een mengsel van Sam Ho en Marcel W's antwoorden, en enkele van mijn eigen bug fixes gedaan om mijn crappy code. Ik was met behulp van een UITableViewController. De tabel verandert nu correct als het toetsenbord wordt weergegeven.

1) viewDidLoadI toegevoegd:

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

2) Ik was vergeten de bellen superequivalenten in viewWillAppearen awakeFromNib. Ik voegde deze opnieuw in.

antwoordde op 26/07/2012 om 18:18
bron van user

stemmen
1

Als uw UITableView wordt beheerd door een subklasse van UITableViewController en niet UITableView en het tekstveld afgevaardigde is de UITableViewController, moet het beheer van alle automatisch scrollen - al deze andere opmerkingen zijn zeer moeilijk toe te passen in de praktijk.

Voor een goed voorbeeld zien van de appel voorbeeldcode project: TaggedLocations.

Je kunt zien dat deze automatisch scrollt, maar er lijkt niet aan een code die dit doet. Dit project heeft ook aangepaste tabelweergave cellen, dus als u uw applicatie te bouwen met het als een gids, moet u het gewenste resultaat te krijgen.

antwoordde op 05/03/2012 om 07:09
bron van user

stemmen
1

Een andere eenvoudige methode (werkt alleen bij een deel)

//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];
antwoordde op 23/11/2011 om 17:25
bron van user

stemmen
1

Dus na uren van slopende werk proberen om deze huidige oplossingen (en volkomen falende) kreeg ik eindelijk dingen goed werken, en ze aangepast aan de nieuwe animatie blokken gebruiken. Mijn antwoord is volledig gebaseerd op het antwoord van Ortwin's hierboven .

Dus voor welke reden dan ook de bovenstaande code was gewoon niet voor mij. Mijn setup leek redelijk vergelijkbaar met anderen, maar misschien omdat ik op een iPad of 4.3 ... geen idee. Het deed wat gekke wiskunde en schieten mijn Tableview van het scherm af.

Zie eindresultaat van mijn oplossing: http://screencast.com/t/hjBCuRrPC (Negeer de foto :-P).

Dus ik ging met de kern van wat Ortwin aan het doen was, maar veranderde hoe het deed wat wiskunde aan de origin.y & size.height van mijn tafel view optellen met de hoogte van het toetsenbord. Toen ik de hoogte van het venster van dat resultaat aftrekken, vertelt me ​​hoeveel kruising Ik heb er aan de hand. Als het groter is dan 0 (aka er enige overlap) I voer de animatie van de framehoogte.

Daarnaast waren er enkele hertekenen problemen die werden opgelost door 1) Wachten om naar de cel te scrollen tot de animatie werd gedaan en 2) met de optie UIViewAnimationOptionBeginFromCurrentState bij het verbergen van het toetsenbord.

Een paar dingen op te merken.

  • _topmostRowBeforeKeyboardWasShown & _originalFrame zijn bijvoorbeeld variabelen in de header verklaard.
  • self.guestEntryTableView is mijn tableView (ik ben in een extern bestand)
  • IASKCGRectSwap is de methode Ortwin voor het wegknippen van de coördinaten van een frame
  • I de hoogte van de tableView werken alleen als ten minste 50 pixels van het gaat laten zien
  • Aangezien ik niet in een UIViewController ik niet self.view, dus ik gewoon de TableView terug te keren naar de originele lijst

Nogmaals, ik zou niet hebben gekregen in de buurt van dit antwoord als ik Ortwin de kern van het niet verstrekken. Hier is de code:

- (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;
}
antwoordde op 18/07/2011 om 09:45
bron van user

stemmen
1

Ik probeerde bijna dezelfde aanpak en kwam met een eenvoudiger en kleinere code voor hetzelfde. Ik heb een IBOutlet iTextView en in verband met de UITextView in de 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];

    }
antwoordde op 13/05/2011 om 06:00
bron van user

stemmen
1

Dit werkt perfect, en op de iPad ook.

- (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];
        }
antwoordde op 23/10/2010 om 08:11
bron van user

stemmen
0

Ik ontdekte gewoon een bug bij het gebruik van UITableViewController. Het was niet automatisch scrollen wanneer het keyboard opdagen. Ik merkte dat het was vanwege contentInsetAdjustmentBehavior = .nooit op UITableView.

antwoordde op 03/07/2019 om 21:30
bron van user

stemmen
0

Oplossing voor Swift 3-4 met animaties en toetsenbord gestel veranderen:

Maak eerst een Bool:

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

Ten tweede, waarnemers toe te voegen aan het systeem Keyboard Kennisgevingen:

// 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)
}

Ten derde, de voorbereiding van de animatie-functie:

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)
}

Voeg vervolgens de doelstelling / actie methoden (genoemd door de waarnemers):

// 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)
        }
    }
}

Tot slot, vergeet dan niet om waarnemers te verwijderen in deinit of in viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}
antwoordde op 10/06/2018 om 15:48
bron van user

stemmen
0

Geen behoefte aan een Berekeningen, Gebruik onderstaande code het zal werken: deze code die ik in mijn Aangepaste UITableViewCell, het werkt:

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)
}}
antwoordde op 22/02/2018 om 07:47
bron van user

stemmen
0

Swift 4 complete oplossing:

  • Correct werkt met toetsenbord gestel veranderingen (bijvoorbeeld toetsenbord hoogteveranderingen zoals emojii → normaal toetsenbord).
  • Tabbalk & ToolBar ondersteuning voor UITableView voorbeeld (bij andere voorbeelden ontvangt u onjuiste inlegwerk).
  • Dynamic duur animatie (niet hard-coded).
  • -Protocol georiënteerde, zodat u gemakkelijk kunt gebruiken in elke situatie.
  • Scroll inzetstukken werkt ook.

Ik schreef helper protocol (je kunt het downloaden als kern , omdat het te groot is om op StackOverflow), zodat uw oog hoeft alleen maar naar:

  1. Vast KeyboardChangeFrameObserverprotocol:

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions)
    
  2. Bel observeKeyboardFrameChanges()op verschijnen.

Voorbeelduitvoeringsvorm van dit protocol voor 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
        })
    }

}
antwoordde op 12/01/2018 om 00:10
bron van user

stemmen
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];
antwoordde op 27/06/2017 om 21:12
bron van user

stemmen
0

Kijk naar mijn versie :)

    - (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];
}
antwoordde op 02/07/2016 om 20:32
bron van user

stemmen
0

Hier is mijn oplossing geïnspireerd door het scherm "Event Edit" van iOS7 Agenda-app.

Een van de belangrijkste punten van deze oplossing is dat het toetsenbord wordt afgewezen wanneer de gebruiker scrollt tabel.

Implementatie:

1) eigenschap die geselecteerde tekstveld zal opslaan toevoegen:

@property (strong) UITextField *currentTextField;

en BOOL variabele die we zullen gebruiken om te controleren of we nodig hebben om het toetsenbord wanneer de gebruiker schuift tafel te verbergen.

BOOL hideKeyboardOnScroll;

2) Handvat UITextField delegeren callbacks:

#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) Handvat UIScrollViewDelegate werkwijze als die gebruiker scroll weergave te controleren.

#pragma mark - UIScrollViewDelegate

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

4) Vraag toetsenbord kennisgevingen ViewController's [viewWillAppear] Werkwijze en afmelden in [viewWillDisappear] werkwijze.

- (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) Handvat toetsenbord meldingen:

- (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;
}
antwoordde op 21/08/2014 om 15:43
bron van user

stemmen
0

Ik denk dat de beste manier is door middel UITableViewController.

Als je een UITableView in een UIViewController willen , gewoon een inhoudAlle met een ingebedde UITableViewController en zet de volgende lijnen in de viedDidLoad van de UIViewController:

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

Gemakkelijk;)

antwoordde op 06/06/2014 om 16:29
bron van user

stemmen
0

Ik denk dat er geen "juiste" manier om dit te doen. Je moet de best passende oplossing voor uw use case te kiezen. In mijn iPad App Ik heb een UIViewControllerdie wordt gepresenteerd modale als UIModalPresentationFormSheeten bestaat uit een UITableView. Deze tabel bevat twee UITextFieldsper cel. Gewoon bellen scrollToRowAtIndexPath:atScrollPosition:animated:in de textFieldDidBeginEditing:methode werkt niet voor mij. Daarom heb ik creëerde een 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];
}

Het idee is dat het toetsenbord verbergt het tableFooterViewen niet het UITextFields. Dus het tableFooterViewmoet hoog genoeg zijn. Daarna kunt u gebruik maken van scrollToRowAtIndexPath:atScrollPosition:animated:de textFieldDidBeginEditing:methode.

Ik denk dat het ook mogelijk om te geven en te verbergen het tableFooterViewdynamisch door toevoeging van de waarnemers voor het toetsenbord meldingen, maar ik heb het nog niet geprobeerd:

- (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];
}
antwoordde op 15/09/2012 om 08:51
bron van user

stemmen
0

ik heb het creëren van een klein project dat dit probleem oplost met het toetsenbord, in mijn geval Ik hoef alleen maar om de tafel uitzicht omhoog gaan als het toetsenbord verschijnt.

Ik hoop dat dit helpt!

http://git.io/BrH9eQ

antwoordde op 19/11/2011 om 21:21
bron van user

stemmen
0

Ik keek weer naar de iOS 5.0 lib referentie en vonden deze sectie met de titel "Moving Content Dat bevindt zich onder het toetsenbord": TextAndWebiPhoneOS KeyboardManagement

Is dit nieuw is sinds iOS 5, misschien? Ik heb nog niet te lezen in het zoals ik ben in het midden van iets anders, maar misschien anderen meer te weten en kan mij en anderen hier te verlichten.

Heeft de Apple doc voorrang op wat er hier besproken of is de informatie die hier nog steeds nuttig om iOS 5 SDK-gebruikers?

antwoordde op 26/10/2011 om 12:07
bron van user

stemmen
0

UITableViewControllerdoet scrollen automatisch inderdaad. Het verschil ten opzichte van het gebruik van een UIViewControlleris, dat je moet navigatiebalk-Buttonitems programmatisch te creëren met behulp van de NavigationController, bij gebruik van een TableViewController.

antwoordde op 20/03/2011 om 20:59
bron van user

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