Uskutečnění UITableView svitek, když je vybráno textové pole

hlasů
228

Po mnoha pokusů a omylů, dávám nahoru a kladl otázky. Viděl jsem mnoho lidí s podobnými problémy, ale nemůže dostat všechny odpovědi správně pracovat.

Mám UITableViewkterá je složena z vlastních buněk. Buňky jsou vyrobeny z 5 textových polí vedle sebe (něco jako mřížky).

Když se snažím posouvat a upravovat buňky v dolní části UITableView, nemohu podaří dostat mé buňky správně umístěny nad klávesnicí.

Viděl jsem mnoho odpovědí hovoří o měnících se velikostí zobrazení, atd ..., ale žádný z nich pracoval dobře tak daleko.

Mohl by někdo objasnit „správný“ způsob, jak to udělat s konkrétním příkladu kódu?

Položena 27/02/2009 v 11:05
zdroj uživatelem
V jiných jazycích...                            


48 odpovědí

hlasů
110

Pokud použijete UITableViewController místo UIViewController, automaticky se tak učinit.

Odpovězeno 21/09/2010 v 04:42
zdroj uživatelem

hlasů
89

Funkce, která se postará o posouvání může být mnohem jednodušší:

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

A je to. Žádné výpočty vůbec.

Odpovězeno 15/04/2009 v 13:21
zdroj uživatelem

hlasů
65

Dělám něco velmi podobného je to obecný, není potřeba počítat něco konkrétního pro váš kód. Stačí si přečíst poznámky na kód:

v 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

v 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+ verze:

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()
        }
    }
}
Odpovězeno 13/04/2010 v 15:46
zdroj uživatelem

hlasů
41

Měl jsem stejný problém, ale všiml si, že se zdá, jen v jednom pohledu. A tak jsem začal hledat rozdíly v řadiči.

Zjistil jsem, že posouvání chování je nastavena - (void)viewWillAppear:(BOOL)animatedna super instance.

Tak se určitě realizovat takto:

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

A nezáleží na tom, pokud používáte UIViewControllernebo UITableViewController; kontroluje ji dosazením UITableViewjako subview z self.view se v UIViewController. Bylo to stejné chování. Pohled nepovolil posouvat v případě, že hovor [super viewWillAppear:animated];byl chybí.

Odpovězeno 29/05/2011 v 01:42
zdroj uživatelem

hlasů
37

Možná jsem vynechal to, jak jsem nečetl celý příspěvek zde, ale to, co jsem přišel s Zdá se zdánlivě jednoduchá. Nemám dát toto přes wringer, testování ve všech situacích, ale zdá se, jako by to mělo fungovat v pohodě.

jednoduše upravit contentInset na TableView výškou klávesnice, a pak přejděte na buňku na dno:

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

a samozřejmě

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

Je to příliš jednoduché? uniká mi něco? Doposud to je práce pro mě v pořádku, ale jak jsem řekl, nemám dát přes wringer ...

Odpovězeno 18/08/2012 v 01:12
zdroj uživatelem

hlasů
35

Nejjednodušší řešení pro Swift 3 , na základě řešení 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)
    })
}
Odpovězeno 08/12/2016 v 13:26
zdroj uživatelem

hlasů
34

Pokud můžete použít UITableViewController, získáte funkce zdarma. Někdy však, že to není možné, zvláště pokud budete potřebovat několik pohledů ne jen UITableView.

Některá řešení zde prezentovaných nefungují na iOS ≥4, některé nefungují na iPadu nebo v režimu na šířku, některé nefungují klávesnic Bluetooth (pokud nechceme některý rolování), některé ne pracovat při přepínání mezi více textových polí. Takže pokud si vyberete nějaké řešení, ujistěte se, že testování těchto případů. Jedná se o řešení, které používáme používá v 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];
    }
}   

Zde je úplný kód třídy v InAppSettingsKit. Chcete-li to vyzkoušet, použijte „Kompletní seznam“ dětský panel, kde si můžete vyzkoušet výše uvedených scénářů.

Odpovězeno 13/12/2010 v 17:01
zdroj uživatelem

hlasů
34

Myslím, že jsem přišel s řešením, aby odpovídalo chování aplikací Apple.

Za prvé, ve svém viewWillAppear: přihlásit k odběru oznámení klávesnice, takže víte, kdy je klávesnice bude zobrazovat a skrývat, a systém vám sdělí velikost klávesnice, ale dont‘zapomněl odhlásit v viewWillDisappear :.

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

Implementovat metody podobné níže, takže můžete nastavit velikost vašeho Tableview tak, aby odpovídala viditelnou oblast jednou klávesových show. Tady jsem sledovat stav klávesnice samostatně, takže můžu zvolit, kdy nastavit Tableview zpět v plné výši sám, protože vám tato oznámení při každé změně pole. Nezapomeňte implementovat keyboardWillHide: a zvolte někde vhodné stanovit svou velikost 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];
    }
}

Tady je rolování bit, nejprve vypracovat několik velikostí, a pak uvidíme, kde jsme ve viditelné oblasti, a nastavit rect chceme přejděte být buď poloviční pohled nad nebo pod střed textového pole na bázi o tom, kde je to v pohledu. V tomto případě máme řadu UITextFields a výčet, který sleduje z nich, takže násobením rowHeight počtem řádků nám dává skutečný posun rámu v rámci tohoto vnějšího pohledu.

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

Zdá se, že funguje docela dobře.

Odpovězeno 23/03/2009 v 02:49
zdroj uživatelem

hlasů
22

Nejjednodušší řešení pro 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
    }
Odpovězeno 25/08/2015 v 06:42
zdroj uživatelem

hlasů
6

Doufám, že vy už mám řešení čtení všech těch. Ale našel jsem řešení takto. Čekám, že již máte buňku UITextField. Takže na přípravu jen držet index řádku do tagu textového pole.

cell.textField.tag = IndexPath.row;

Vytvořit activeTextField, instanci UITextFields globálním rozsahem jak je uvedeno níže:

@interface EditViewController (){

    UITextField *activeTextField;

}

Tak, teď stačí zkopírovat vložit svůj kód na konci. A také nezapomeňte přidatUITextFieldDelegate

#pragma mark - TextField Delegation

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

    activeTextField = textField;

    return YES;
}

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

    activeTextField = nil;

}

registry klávesnice 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];



}

Kliky klávesnice Notifications:

Volána, když UIKeyboardDidShowNotificationje poslal.

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

}

Volána, když UIKeyboardWillHideNotificationje odeslána

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

}

Nyní jedna věc zbývá, volejte registerForKeyboardNotificationsmetodu k ViewDidLoadmetodě takto:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Registering keyboard notification

    [self registerForKeyboardNotifications];

    // Your codes here...

}

Co jste udělal, doufám, že vaše textFieldsvůle už není skryta klávesnice.

Odpovězeno 03/01/2015 v 21:36
zdroj uživatelem

hlasů
6

Kombinování a bude vyplňovat prázdná místa z několika odpovědí (zejména Ortwin Gentz, uživatelské 98013) a jiné místo, to bude fungovat po vybalení z krabice pro SDK 4.3 na iPad ve výšku i na šířku:

@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
Odpovězeno 03/08/2011 v 03:35
zdroj uživatelem

hlasů
5

Můj přístup:

Poprvé jsem podtřídy UITextField a přidat vlastnost indexPath. V cellFor ... Method i předat vlastnost indexPath.

Pak jsem přidat následující kód:

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

na textFieldShould / WillBegin ... atd.

Je-li klávesnice zmizí budete muset obrátit na:

[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, 0);}];
Odpovězeno 29/09/2012 v 13:03
zdroj uživatelem

hlasů
4

Použít UITextField's delegatemetodu:

Rychlý

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;
}
Odpovězeno 20/03/2015 v 07:00
zdroj uživatelem

hlasů
4

Správná odpověď je Sama Ho odpověď:

„Pokud používáte UITableViewController místo UIViewController, automaticky se tak učinit.“.

Jen nezapomeňte připojit UITableView na majetku Tableview na UITableViewController (takže např nepřidávejte ji jako subview toho názoru majetku UITableViewController).

Také nezapomeňte nastavit vlastnost AutoresizingMask svého UITableView na FlexibleHeight

Odpovězeno 09/12/2010 v 11:28
zdroj uživatelem

hlasů
4

Pokud použijete Three20, pak použijte autoresizesForKeyboardvlastnost. Stačí nastavit v této vašeho názoru regulátoru -initWithNibName:bundlemetodou

self.autoresizesForKeyboard = YES

To se stará o:

  1. Posloucháním oznámení klávesnice a nastavení rámu pohledu tabulky je
  2. Posouvání první odpovídač

Hotovo a hotovo.

Odpovězeno 21/09/2010 v 14:19
zdroj uživatelem

hlasů
4

Oznámení klávesnice fungovat, ale Apple ukázkový kód, který předpokládá, že pohled na svitek je kořenem pohled z okna. To je obvykle není tento případ. Budete muset kompenzovat karta bary, atd, aby se právo offset.

Je to jednodušší, než se zdá. Zde je kód mám použít v UITableViewController. Má dvě proměnné instance, hiddenRect a 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;
}
Odpovězeno 11/07/2009 v 23:01
zdroj uživatelem

hlasů
4

Pokud použijete uitableview umístit TextováPole ( od Jeff Lamarche ), můžete prostě rolovat Tableview pomocí metody delegáta takhle.

(Poznámka: moje textová pole jsou uloženy v poli se stejným indexem protože řádek v 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];
    }
Odpovězeno 01/05/2009 v 07:09
zdroj uživatelem

hlasů
3

Více roztok proud vložkou. To vklouzne do metod UITextField delegáta, takže nevyžaduje probírat w / oznámení UIKeyboard.

poznámky Realizace:

kSettingsRowHeight - výška v UITableViewCell.

offsetTarget a offsetThreshold jsou baed pryč kSettingsRowHeight. Pokud použijete jinou výšku řádku, nastavte tyto hodnoty na bod v y majetku. [Alt: vypočítat řádek offset jiným způsobem.]

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

}

Odpovězeno 04/08/2009 v 08:18
zdroj uživatelem

hlasů
3

Narazil jsem na něco podobného problému (chtěl jsem obrazovku podobnou iPhone settings.app s partou editovatelných buněk naskládaných na na sebe), a zjistil, že tento přístup funguje dobře:

posuvné uitextfields kolem, aby se zabránilo

Odpovězeno 27/02/2009 v 15:17
zdroj uživatelem

hlasů
2

Jako příklad v Swift, používat přesný bod textového pole od Get indexPath z UITextField v UITableViewCell s 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)
}
Odpovězeno 21/05/2015 v 06:34
zdroj uživatelem

hlasů
2

Velmi zajímavá diskuse nit, jsem také čelí Stejný problém může být ještě horší, protože jedna

  1. Byl jsem pomocí vlastní buňky a textfield byl uvnitř to.
  2. Musel jsem použít UIViewController splnit mé požadavky, takže převýšení využít UITableViewController.
  3. Měl jsem filtr / třídění Charakteristiky v mém buňky tabulky, tj ur buňky neustále mění a udržování přehledu o indexpath a vše nepomůže.

Tak čtěte vlákna zde a realizovány mou verzi, která mi pomohla při prosazování mé obsah v iPadu na šířku režimu. Zde je kód (to není blázen důkaz a vůbec, ale to pevné můj problém) Za prvé u potřeba mít delegát ve své třídě zvykem buněk, které při editaci začíná, odešle doplníme ur viewcontroller a nastavit activefield = theTextField tam

// REALIZOVÁNY zvládnout režim Krajina ONLY

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

    }


}

// Called po odeslání UIKeyboardWillHideNotification

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

Odpovězeno 17/07/2012 v 18:11
zdroj uživatelem

hlasů
2

To soluton pracuje pro mě, prosím, na vědomí linku

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

Můžete změnit hodnotu 160 tak, aby odpovídala, že pracovat s vámi

- (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];
}
Odpovězeno 02/12/2011 v 19:28
zdroj uživatelem

hlasů
2

Vzhledem k tomu, máte TextováPole v tabulce, nejlepší způsob, jak skutečně změnit velikost stolu - je třeba znovu nastavit tableView.frame být menší výšku podle velikosti klávesnice (myslím, že asi 165 pixelů) a potom položku, když klávesnice se zamítá.

Volitelně můžete také zakázat interakci s uživatelem pro Tableview v té době stejně, pokud nechcete uživatelské rolování.

Odpovězeno 28/02/2009 v 19:37
zdroj uživatelem

hlasů
1

Malá změna se Swift 4.2 ...

Na mém UITableView jsem měl mnoho částí, ale musel jsem se vyhnout plovoucí záhlaví efektu , takže jsem použil „ dummyViewHeight přístupu“, jak je vidět někde jinde zde na přetečení zásobníku ... Tak tohle je moje řešení tohoto problému (funguje i pro klávesnici + Panel + doporučení):

Deklarovat jako třída konstanta:

let dummyViewHeight: CGFloat = 40.0

Pak

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

A tady všechno kouzlo ...

@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)
    }
}
Odpovězeno 08/10/2018 v 10:45
zdroj uživatelem

hlasů
1

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







    }
Odpovězeno 12/02/2016 v 09:14
zdroj uživatelem

hlasů
1

Já používám tyto a fungují jako kouzlo:

BSKeyboardControls - BSKeyboardControls GitHub

TPKeyboardAvoiding - TPKeyboardAvoiding GitHub

Odpovězeno 13/02/2014 v 09:30
zdroj uživatelem

hlasů
1

Používám to často ve svých projektech. Toto řešení pracuje s scrollviews, tableviews nebo collectionviews a je snadné nastavení. Také automaticky zahákne tlačítka nahoru „Další“ na klávesnici pro přepínání pomocí textových polí.

Ověřte si to zde

Odpovězeno 12/02/2014 v 21:27
zdroj uživatelem

hlasů
1

Budu házet moje řešení (nebo QuickDialog to, že je) do klobouku. V podstatě se dočkat, až animovat k rolování. Bylo by hezké dostat klávesnice animace JIT namísto magického čísla.

-(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];
        });
    }
}
Odpovězeno 28/01/2014 v 19:05
zdroj uživatelem

hlasů
1

Snadné a rychlé řešení.

Jen jsem přejděte na pravou buňkou kdykoli posouvání děje

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView 

Za předpokladu, že vím, že tabulka je nyní v tomto režimu „_keepMyCellOnTop“ a vím, že vybrané buňky „_selectedCellIndex“ nebo přejděte na vybrané buňky

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

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

Tím se zabrání posouvání.

Umístěním kód -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView bude mít za následek svitek nahoru a dolů

Odpovězeno 31/12/2013 v 13:37
zdroj uživatelem

hlasů
1

Právě jsem vyřešil takový problém sám poté, co jsem se zmínil o hmotnosti řešení zjištěných přes Google a přetečení zásobníku.

Za prvé, prosím, ujistit, že jste nastavit IBOutlet svého UIScrollView, pak prosím, se blíže podívat na Apple Doc: Správa klávesnice . A konečně, pokud můžete rolovat na pozadí, ale klávesnice stále pokrývá textových polí, prosím, podívejte se na tuto část kódu:

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

Hlavní rozdíl mezi touto částí a Apple spočívá v Pokud je podmínka. Věřím, že výpočet Apple tohoto posuvníku vzdálenosti a stavu, zda textové pole pokryta klávesnice nejsou přesné, takže jsem udělal můj modifikaci jak je uvedeno výše.

Dejte mi vědět, jestli to funguje

Odpovězeno 18/08/2012 v 11:10
zdroj uživatelem

hlasů
1

Zde je, jak jsem tuto práci, která je směsí Sama Ho a odpovědi Marcela W je a některé z mých vlastních chyb z mého mizerný kódu. Byl jsem pomocí UITableViewController. V tabulce se změní velikost správně, pokud se zobrazí klávesnice.

1) V viewDidLoadI zní:

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

2) jsem zapomněl zavolat superekvivalenty v viewWillAppeara awakeFromNib. Přidal jsem tyto zpět.

Odpovězeno 26/07/2012 v 18:18
zdroj uživatelem

hlasů
1

Je-li váš UITableView řízena podtřídy UITableViewController a nikoliv UITableView a textové pole delegáta je UITableViewController by měl řídit celý rolování automaticky - všechny tyto další připomínky jsou velmi obtížně proveditelná v praxi.

Za dobrý příklad vidět jablko projekt příklad kódu: TaggedLocations.

Můžete vidět, že se posouvá automaticky, ale nezdá se, že by kód, který to dělá. Tento projekt má také buňky zobrazení vlastního stolu, takže pokud budete stavět svou aplikaci s ním jako vodítko, měli byste získat požadovaný výsledek.

Odpovězeno 05/03/2012 v 07:09
zdroj uživatelem

hlasů
1

Další snadný způsob (funguje pouze u jedné sekce)

//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];
Odpovězeno 23/11/2011 v 17:25
zdroj uživatelem

hlasů
1

Takže po hodinách vysilující práce se snaží používat tyto stávající řešení (a naprosto selhává) jsem se konečně dostal, co funguje dobře, a aktualizuje je, aby používaly nové animace bloky. Moje odpověď je založen výhradně na ORTWIN své odpovědi výše .

Takže z jakéhokoliv důvodu výše uvedený kód byl prostě není práce pro mě. Moje volby zdálo docela podobný ostatním, ale možná proto, že jsem byl na iPadu nebo 4.3 ... tušení. To dělal nějaký nezvyklý matematiku a střílí svůj Tableview mimo obrazovku.

Viz konečný výsledek mé řešení: http://screencast.com/t/hjBCuRrPC (Prosím ignorovat foto :-P).

Tak jsem šel s podstaty toho, co Ortwin dělal, ale změnil jak to dělá nějaký matematický sečíst origin.y & size.height mého stolu pohledu s výškou klávesnice. Když jsem odečíst výšku okna z tohoto výsledku, to mi říká, jak moc křižovatky jsem se děje. Je-li jeho větší než 0 (aka tam je nějaké překrývání) jsem provést animaci výšky rámu.

Kromě toho byly některé překreslení problémy, které byly vyřešeny 1) Čekací přejděte do buňky, dokud animace bylo provedeno a 2) pomocí volby UIViewAnimationOptionBeginFromCurrentState při skrývání klávesnice.

Pár věcí, které na vědomí.

  • _topmostRowBeforeKeyboardWasShown & _originalFrame jsou instance proměnné deklarované v záhlaví.
  • self.guestEntryTableView je můj Tableview (jsem v externím souboru)
  • IASKCGRectSwap je ORTWIN metoda pro obracející souřadnic rámu
  • Já jen aktualizovat výšku Tableview, pokud alespoň 50 pixelů z toho se bude zobrazovat
  • Vzhledem k tomu, že nejsem v UIViewController nemám self.view, a tak jsem jen vrátit Tableview do původního rámu

Opět platí, že bych se mohla dostat blízko tuto odpověď, kdybych Ortwin neposkytl těžiště ní. Zde je kód:

- (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;
}
Odpovězeno 18/07/2011 v 09:45
zdroj uživatelem

hlasů
1

Snažil jsem se skoro stejný přístup a přišel s jednodušší a menší kód pro totéž. Vytvořil jsem IBOutlet iTextView a spojený s UITextView v 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];

    }
Odpovězeno 13/05/2011 v 06:00
zdroj uživatelem

hlasů
1

To funguje perfektně, a iPad taky.

- (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];
        }
Odpovězeno 23/10/2010 v 08:11
zdroj uživatelem

hlasů
0

Právě jsem objevil další chybu při používání UITableViewController. Bylo neposouvá automaticky, když klávesnice neukázal. Všiml jsem si, že to bylo kvůli contentInsetAdjustmentBehavior = .never na UITableView.

Odpovězeno 03/07/2019 v 21:30
zdroj uživatelem

hlasů
0

Řešení pro Swift 3-4 s animací a změnu klávesnice rámu:

Nejprve vytvořte Bool:

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

Za druhé, přidejte pozorovatelů na systémové klávesnice Upozornění:

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

Za třetí, připravit funkci animace:

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

Pak přidáme metody target / akční (nazývané podle pozorovatelů):

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

A konečně, nezapomeňte odstranit pozorovatelů deinit nebo viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}
Odpovězeno 10/06/2018 v 15:48
zdroj uživatelem

hlasů
0

Není potřeba žádné výpočty, použijte pod kódem to bude fungovat: Tento kód jsem použil v mém Zákaznické UITableviewcell, to funguje:

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)
}}
Odpovězeno 22/02/2018 v 07:47
zdroj uživatelem

hlasů
0

Swift 4 kompletní řešení:

  • Správně pracuje se změnami rámu klávesnice (např výška klávesnice se změní jako emojii → normální klávesnici).
  • Tabbar & ToolBar podpora UITableView příkladu (v jiných příkladech obdržíte nesprávné vložek).
  • Dynamická doba animace (není pevně).
  • Protokol orientovaný, takže můžete snadno použít v každé situaci.
  • Scroll vložky funguje taky.

Napsal jsem pomocníka protokol (můžete si jej stáhnout jako GIST , protože je příliš velký, aby příspěvek na StackOverflow), tak podle vašeho názoru stačí, aby:

  1. Přijímá KeyboardChangeFrameObserverprotokol:

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions)
    
  2. Volejte observeKeyboardFrameChanges()na objevit.

Příklad provedení tohoto protokolu pro 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
        })
    }

}
Odpovězeno 12/01/2018 v 00:10
zdroj uživatelem

hlasů
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];
Odpovězeno 27/06/2017 v 21:12
zdroj uživatelem

hlasů
0

Podívejte se na mé verzi :)

    - (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];
}
Odpovězeno 02/07/2016 v 20:32
zdroj uživatelem

hlasů
0

Tady je moje řešení inspirovaný obrazovce „Upravit událost“ z iOS7 aplikaci Kalendář.

Jedním z klíčových bodů tohoto řešení je, že klávesnice je propuštěn když uživatel při posouvání stolu.

Implementace:

1) Přidat vlastnost, která bude ukládat vybraný doplníme:

@property (strong) UITextField *currentTextField;

a BOOL proměnnou, která budeme používat pro kontrolu, zda musíme schovat klávesnice, když uživatel posouvá tabulky.

BOOL hideKeyboardOnScroll;

2) Při manipulaci UITextField delegáta zpětná volání:

#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) Rukojeť metodu UIScrollViewDelegate pro kontrolu, zda uživatel rolování názor.

#pragma mark - UIScrollViewDelegate

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

4) Přihlašte se na oznámení klávesnice v [viewWillAppear] metody viewcontroller a odhlásit v [viewWillDisappear] metody.

- (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) Rukojeť oznámení klávesnice:

- (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;
}
Odpovězeno 21/08/2014 v 15:43
zdroj uživatelem

hlasů
0

Myslím, že nejlepší cesta je přes UITableViewController.

Pokud chcete, aby UITableView v UIViewController , jen aby si contentView s vloženým UITableViewController a dát následující řádky v viedDidLoad na UIViewController:

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

Easy)

Odpovězeno 06/06/2014 v 16:29
zdroj uživatelem

hlasů
0

Myslím, že neexistuje žádný „správný“ způsob, jak to udělat. Musíte si vybrat nejvhodnější řešení pro váš případ použití. V mém iPad App Mám UIViewControllerkterý je prezentován jako modální UIModalPresentationFormSheeta sestává z UITableView. Tato tabulka obsahuje dva UITextFieldsna buňku. Jen volání scrollToRowAtIndexPath:atScrollPosition:animated:v textFieldDidBeginEditing:metoda nefunguje pro mě. Proto jsem vytvořil 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];
}

Předpokládá se, že klávesnice skryje tableFooterViewa nikoliv UITextFields. Takže tableFooterViewmusí být dostatečně vysoká. Poté, které můžete použít scrollToRowAtIndexPath:atScrollPosition:animated:v textFieldDidBeginEditing:metodě.

Myslím, že je také možné zobrazit a skrýt tableFooterViewdynamicky přidáním pozorovatele pro oznamování klávesové ale ještě jsem to zkusil:

- (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];
}
Odpovězeno 15/09/2012 v 08:51
zdroj uživatelem

hlasů
0

Udělal jsem vytvořit malý projekt, který řeší tento problém s klávesnicí, v mém případě i jen třeba, aby se pohled tabulka jít nahoru, když se klávesnice objeví.

Snad to pomůže!

http://git.io/BrH9eQ

Odpovězeno 19/11/2011 v 21:21
zdroj uživatelem

hlasů
0

Jen jsem se znovu podíval do iOS 5.0 lib reference a našel tento oddíl s názvem „Moving obsah, který je umístěn pod klávesnicí“: TextAndWebiPhoneOS KeyboardManagement

Je to nový od iOS 5, snad? Nečetl jsem do toho ještě, že jsem uprostřed něčeho jiného, ​​ale možná jiní vědět víc a mě i ostatní mohou poučit zde.

Má Apple doc přednost, co se zde hovoří, nebo je informace zde ještě užitečný pro uživatele iOS 5 SDK?

Odpovězeno 26/10/2011 v 12:07
zdroj uživatelem

hlasů
0

UITableViewControllerdělá Scrolling automaticky, opravdu. Rozdíl ve srovnání s použitím UIViewControllerje to, že budete muset vytvořit NavBar-Buttonitems programově pomocí NavigationController, když pomocí TableViewController.

Odpovězeno 20/03/2011 v 20:59
zdroj uživatelem

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