[ios] 아이폰 키보드 UITextField 커버

Interface BuilderUIView 에서보기 하단 근처에 텍스트 필드가있는을 설정 한 앱 이 있습니다. 앱을 실행하고 해당 필드에 텍스트를 입력하려고하면 키보드가 필드 위로 미끄러 져서 키보드를 다시 숨길 때까지 입력중인 내용을 볼 수 없습니다.

다른 사람이이 문제를 겪고 부모보기를 스크롤 가능하게 만들거나 텍스트 필드를 화면 위로 이동하지 않고도 문제를 해결할 수있는 좋은 방법을 찾았습니까?



답변

일반적인 해결 방법은 애니메이션을 사용하여 필드 (및 그 위에있는 모든 항목)를 위로 밀었 다가 완료되면 아래로 내리는 것입니다. 텍스트 필드와 일부 다른 항목을 다른보기에 넣고보기를 하나의 단위로 밀어야 할 수 있습니다. (나는 이것을 “접착 판”에서와 같이 “판”이라고 부르지 만 그것은 나 뿐이다). 그러나 여기에 당신이 공상을 할 필요가 없다면 일반적인 아이디어가 있습니다.

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}


답변

이것은 uitextfields 슬라이딩 나를 위해 놀라운 일을했습니다.

특히 텍스트 필드의 위치에 따라 슬라이드 애니메이션 거리를 계산하는 이점이 있습니다.


답변

IQKeyboardManager코드없이이 작업을 수행합니다 . 관련 소스 파일을 프로젝트로 끌어서 놓기 만하면 됩니다. IQKeyboardManager 는 또한 Device Orientation , Automatic UIToolbar Management , keyboardDistanceFromTextField 및 생각보다 훨씬 많은 것을 지원합니다.

여기에 이미지 설명 입력

다음은 제어 흐름 차트입니다.
제어 흐름 차트

1 단계는 : – 글로벌 알림을 추가 UITextField, UITextViewUIKeyboard싱글 클래스. 나는 그것을 IQKeyboardManager 라고 불렀습니다 .

2 단계 :- 발견 된 UIKeyboardWillShowNotification경우 UITextFieldTextDidBeginEditingNotification또는 알림이있는 경우 계층 구조 에서 인스턴스 UITextViewTextDidBeginEditingNotification를 가져 오십시오 . 제대로 밝히기 위해서는 / 그것에서 의 프레임을 조정해야합니다.topMostViewControllerUIWindow.rootViewControllerUITextFieldUITextViewtopMostViewController.view

Step3 :-topMostViewController.view 첫 번째 응답 UITextField/에 대한 예상 이동 거리 계산 UITextView.

Step4 :-topMostViewController.view.frame 예상 이동 거리에 따라 위 / 아래 로 이동 했습니다.

5 단계 : – 발견하는 경우 UIKeyboardWillHideNotification, UITextFieldTextDidEndEditingNotification또는 UITextViewTextDidEndEditingNotification통지 후 다시 얻으려고 topMostViewController로부터 인스턴스를 UIWindow.rootViewController계층 구조.

Step6 :-topMostViewController.view 원래 위치로 복원해야하는 계산 된 방해 거리 .

Step7 :-topMostViewController.view.frame 방해 된 거리에 따라 아래로 복원 .

Step8 :- 앱로드시 인스턴스화 된 싱글 톤 IQKeyboardManager 클래스 인스턴스이므로 앱의 모든 UITextField/ UITextView가 예상 이동 거리에 따라 자동으로 조정됩니다.

그게 다야


답변

Amagrammer 답변을 확장하려면 다음은 샘플 클래스입니다.

LoginViewController.h

@interface LoginViewController : UIViewController <UITextFieldDelegate> {

}

@property (nonatomic, retain) IBOutlet UITextField    *emailTextField;
@property (nonatomic, retain) IBOutlet UITextField    *passwordTextField;

“UITextFieldDelegate”를 구현하고 있습니다.

LoginViewController.m

@implementation LoginViewController
@synthesize emailTextField=_emailTextField;
@synthesize passwordTextField=_passwordTextField;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //Register to receive an update when the app goes into the backround
        //It will call our "appEnteredBackground method
        [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appEnteredBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    }
    return self;
}


- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
//This is called when the app goes into the background.
//We must reset the responder because animations will not be saved
- (void)appEnteredBackground{
    [self.emailTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}


답변

공식 솔루션은 어떻습니까 : 키보드 아래에있는 콘텐츠 이동

콘텐츠를 조정하려면 일반적으로 하나 이상의보기 크기를 일시적으로 조정하고 텍스트 개체가 계속 표시되도록 배치합니다. 키보드로 텍스트 개체를 관리하는 가장 간단한 방법은 UIScrollView 개체 (또는 UITableView와 같은 하위 클래스 중 하나)에 포함하는 것입니다. 키보드가 표시되면 스크롤보기의 콘텐츠 영역을 재설정하고 원하는 텍스트 개체를 위치로 스크롤하기 만하면됩니다. 따라서 UIKeyboardDidShowNotification에 대한 응답으로 처리기 메서드는 다음을 수행합니다.

  1. 키보드의 크기를 확인하십시오.
  2. 스크롤보기의 하단 내용 삽입을 키보드 높이로 조정합니다.
  3. 대상 텍스트 필드를보기로 스크롤합니다.
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification 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:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

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

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}


답변

UITableView textField 셀 에서 동일한 문제에 직면했습니다 . 키보드 알림을 듣기 위해 다음 방법을 구현하여이 문제를 해결합니다.

여기에서 알림에 대한 관찰자 :

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

아래 기능을 사용하여 해당 알림을 처리하십시오.

(void)keyboardWasShown:(NSNotification*)aNotification
(void)keyboardWillBeHidden:(NSNotification*)aNotification 


답변

이것 좀 봐. 번거롭지 않습니다.

이 솔루션은 매우 깔끔합니다. 스토리 보드를 사용하는 경우 a에 텍스트 필드를 추가 UIScrollView하고 클래스를로 변경 하기 만하면됩니다 TPKeyboardAvoidingScollView. 스크롤 뷰는 키보드가 보일 때를 감지하고 적당한 거리에서 키보드 위로 스스로 이동하는 방식으로 확장됩니다. .NET Framework와 독립적이기 때문에 완벽한 솔루션 UIViewController입니다. 필요한 모든 것은 위에서 언급 한 클래스 내에서 수행됩니다. 감사합니다 Michael Tyson et all.

TPKeyboardAvoiding