簡體   English   中英

鍵盤顯示時嘗試向上移動視圖

[英]Trying to move the view up when the keyboard is showing

我試圖在鍵盤顯示時向上推動我的視圖(它覆蓋了我希望用戶在鍵入時看到的數據。我正在使用此代碼:

KBKeyboardHandler.h

@protocol KBKeyboardHandlerDelegate;

@interface KBKeyboardHandler : NSObject

- (id)init;

// Put 'weak' instead of 'assign' if you use ARC
@property(nonatomic, assign) id<KBKeyboardHandlerDelegate> delegate; 
@property(nonatomic) CGRect frame;

@end

KBKeyboardHandler.m

#import "KBKeyboardHandler.h"
#import "KBKeyboardHandlerDelegate.h"

@implementation KBKeyboardHandler

- (id)init
{
    self = [super init];
    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];

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

    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

@synthesize delegate;
@synthesize frame;

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGRect oldFrame = self.frame;    
    [self retrieveFrameFromNotification:notification];

    if (oldFrame.size.height != self.frame.size.height)
    {
        CGSize delta = CGSizeMake(self.frame.size.width - oldFrame.size.width,
                                  self.frame.size.height - oldFrame.size.height);
        if (self.delegate)
            [self notifySizeChanged:delta notification:notification];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    if (self.frame.size.height > 0.0)
    {
        [self retrieveFrameFromNotification:notification];
        CGSize delta = CGSizeMake(-self.frame.size.width, -self.frame.size.height);

        if (self.delegate)
            [self notifySizeChanged:delta notification:notification];
    }

    self.frame = CGRectZero;
}

- (void)retrieveFrameFromNotification:(NSNotification *)notification
{
    CGRect keyboardRect;
    [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardRect];
    self.frame = [[UIApplication sharedApplication].keyWindow.rootViewController.view convertRect:keyboardRect fromView:nil];
}

- (void)notifySizeChanged:(CGSize)delta notification:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];

    UIViewAnimationCurve curve;
    [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];

    NSTimeInterval duration;
    [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];

    void (^action)(void) = ^{
        [self.delegate keyboardSizeChanged:delta];
    };

    [UIView animateWithDuration:duration
                          delay:0.0
                        options:curve
                     animations:action
                     completion:nil];    
}

@end

KBKeyboardHandlerDelegate.h

@protocol KBKeyboardHandlerDelegate

- (void)keyboardSizeChanged:(CGSize)delta;

@end

示例MyViewController.h

@interface MyViewController : UIViewController<KBKeyboardHandlerDelegate>
...
@end

示例MyViewController.m

@implementation MyViewController
{
    KBKeyboardHandler *keyboard;
}

- (void)dealloc
{
    keyboard.delegate = nil;
    [keyboard release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    keyboard = [[KBKeyboardHandler alloc] init];
    keyboard.delegate = self;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    keyboard.delegate = nil;
    [keyboard release];
    keyboard = nil;
}

- (void)keyboardSizeChanged:(CGSize)delta
{
    // Resize / reposition your views here. All actions performed here 
    // will appear animated.
    // delta is the difference between the previous size of the keyboard 
    // and the new one.
    // For instance when the keyboard is shown, 
    // delta may has width=768, height=264,
    // when the keyboard is hidden: width=-768, height=-264.
    // Use keyboard.frame.size to get the real keyboard size.

    // Sample:
    CGRect frame = self.view.frame;
    frame.size.height -= delta.height;
    self.view.frame = frame;
}

我在這里找到 我想弄清楚為什么我的觀點沒有推高。 鍵盤正在顯示,並且keyboardSizeChanged已啟動,但視圖不會移動。 我打開了一個新項目並復制了KBKeyboardHandler並將文件委托給它,實現了代碼,並且在新項目中它運行正常,所以我知道這是一個事實,它在我原來的項目中被搞砸了。 知道它可以是什么嗎?

如果您沒有使用UITableView,請使用UIScrollView作為元素的父視圖,並根據需要添加以下代碼,

您將需要一個NSObject的NSArray,我調用了我的scrollToObjects,並在viewDidLoad中將元素添加到需要滾動的數組中,這樣當調用keyboardWasShown時,您可以檢查是否應該滾動到當前選定的元素。

我使用self.activeField來存儲我當前選中的元素,該元素在元素觸發事件時設置(事件需要是第一個調用的事件之一,並且總是被調用)

然后我檢查scrollToObjects是否包含activeField以及它是否向上滾動UIScrollView然后在activeField resignsFirstResponder時向下滾動

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

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

    // 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;
    // Wouldn't go true so used an array that contains text fields that need to be scrolled   to
    //    if (!CGRectContainsPoint(aRect, self.activeField.frame.origin) ) {
    //        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-    kbSize.height);
    //        [self.scrollView setContentOffset:scrollPoint animated:YES];
    //    }
    if ([self.scrollToObjects containsObject:self.activeField]) {
        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y+    (self.activeField.frame.size.height*2)-kbSize.height);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent 
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{ 
    // self.scrollView.contentInset = UIEdgeInsetsZero;
    [self.scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
    self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

一個更簡單的解決方案是使用以下代碼或類似於激活和停用對象的代碼來處理下面的UITextFieldDelegate方法

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGPoint scrollPoint = CGPointMake(0.0, textField.frame.origin.y);
    [self.theScrollView setContentOffset:scrollPoint animated:YES];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.theScrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
    self.theScrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

我會檢查你的delta計算。

CGSize delta = CGSizeMake(self.frame.size.width - oldFrame.size.width,
                              self.frame.size.height - oldFrame.size.height);

我的猜測是oldFrameself.frame可能具有相同的尺寸。

我正在考慮是否還有其他任何可能遺漏的內容,比如將視圖正確鏈接到這些對象或界面編輯器中的某些內容?

問題在於keyboardSizeChanged: - 您要調整的是frame.origin.y,而不是frame.size.height。 至少這就是想要的。

您也可以嘗試另一個庫,它叫做TPKeyboardAvoiding 它工作得很好,而且很容易設置:

  1. 將UIScrollView添加到視圖控制器的xib中
  2. 將滾動視圖的類設置為TPKeyboardAvoidingScrollView(仍然在xib中,通過身份檢查器)
  3. 將所有控件放在該滾動視圖中

它還會自動連接鍵盤上的“下一步”按鈕以切換文本字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM