Programing

iOS에서 UIKeyboard 크기를 얻는 방법

lottogame 2020. 11. 13. 07:43
반응형

iOS에서 UIKeyboard 크기를 얻는 방법


프로그래밍 방식으로 UIKeyboard 크기를 얻는 방법이 있습니까? 가로 216.0f 및 높이 162.0f.

다음은 더 이상 사용되지 않는 것 같습니다. 3.0 iPhone OS SDK 및 4.0 iPhone OS SDK에서 경고없이 작동하는 방법이 있습니까?

CGSize keyBoardSize = [[[note userInfo]
                        objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;

당신은에서 키보드의 크기를 얻을 수 있습니다 userInfo사용하여 사전 UIKeyboardFrameBeginUserInfoKeyUIKeyboardFrameEndUserInfoKey 대신합니다.

이 두 키 는 키보드 표시 / 숨기기 애니메이션의 시작 지점과 끝 지점 모두에서 키보드의 위치와 크기를 NSValue포함 하는 인스턴스를 반환합니다 CGRect.

편집하다:

명확히하기 위해 userInfo사전은 NSNotification 인스턴스 에서 가져옵니다 . 관찰자에게 등록하는 메서드에 전달됩니다. 예를 들면

- (void)someMethodWhereYouSetUpYourObserver
{
    // This could be in an init method.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                    selector:@selector(myNotificationMethod:) 
                    name:UIKeyboardDidShowNotification 
                    object:nil];
}

- (void)myNotificationMethod:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}

편집 2 :

또한 dealloc방법 에서 관찰자로서 자신을 제거하는 것을 잊지 마십시오 ! 이는 알림 센터가 해제 된 후 개체에 알림을 보내려고 할 때 발생하는 충돌을 방지하기위한 것입니다.


당신은을 사용해야합니다 UIKeyboardWillChangeFrameNotification일부 국제 키보드는, 중국의 키보드처럼 사용하는 동안 프레임을 변경할 수 있기 때문에, 대신. 또한 CGRect가로 사용을 위해를 적절한보기로 변환해야 합니다.

//some method like viewDidLoad, where you set up your observer.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

- (void)keyboardWillChange:(NSNotification *)notification {
    CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it!
}

내가 마침내 작품을 만든 방법은 다음과 같습니다. 나는 다른 답변의 제안과 코드를 결합했습니다. 기능 : "다음"및 "완료"키보드 반환 유형을 편집하고 설정하는 동안 키보드 해제, 키보드 위로 텍스트 필드 이동. 더 많은 필드로 "..."바꾸기

static const CGFloat ANIMATION_DURATION = 0.4;
static const CGFloat LITTLE_SPACE = 5;
CGFloat animatedDistance;
CGSize keyboardSize;

@interface ViewController () <UITextFieldDelegate>
 @property (weak, nonatomic) IBOutlet UITextField *firstNameTXT;
  .....// some other text fields
 @property (weak, nonatomic) IBOutlet UITextField *emailTXT;
@end

@implementation ViewController
- (void)viewDidLoad{
.....
// add tap gesture to help in dismissing keyboard
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(tapScreen:)];// outside textfields

[self.view addGestureRecognizer:tapGesture];

// set text fields return key type to Next, last text field to Done
[self.firstNameTXT setReturnKeyType:UIReturnKeyNext];
.....
[self.emailTXT setReturnKeyType:UIReturnKeyDone];

// set text fields tags
[self.firstNameTXT setTag:0];
....// more text fields
[self.emailTXT setTag:5];

// add keyboard notification
[[NSNotificationCenter defaultCenter] addObserver:self     selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self      selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

// dismiss keyboard when tap outside text fields
- (IBAction)tapScreen:(UITapGestureRecognizer *)sender {
  if([self.firstNameTXT isFirstResponder])[self.firstNameTXT resignFirstResponder];
  ...
  if([self.emailTXT isFirstResponder])[self.emailTXT  resignFirstResponder];

  }
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
   if(textField.returnKeyType==UIReturnKeyNext) {
     // find the text field with next tag
     UIView *next = [[textField superview] viewWithTag:textField.tag+1];
     [next becomeFirstResponder];
   } else if (textField.returnKeyType==UIReturnKeyDone || textField.returnKeyType==UIReturnKeyDefault) {
    [textField resignFirstResponder];
 }
return YES;
}

// Moving current text field above keyboard
-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField{
   CGRect viewFrame = self.view.frame;
   CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
   CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
   CGFloat textFieldBottomLine = textFieldRect.origin.y + textFieldRect.size.height + LITTLE_SPACE;//

   CGFloat keyboardHeight = keyboardSize.height;

   BOOL isTextFieldHidden = textFieldBottomLine > (viewRect.size.height - keyboardHeight)? TRUE :FALSE;
  if (isTextFieldHidden) {
    animatedDistance = textFieldBottomLine - (viewRect.size.height - keyboardHeight) ;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
  }
  return YES;
}

-(void) restoreViewFrameOrigionYToZero{
  CGRect viewFrame = self.view.frame;
  if (viewFrame.origin.y != 0) {
    viewFrame.origin.y = 0;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
  }
}

-(void)keyboardDidShow:(NSNotification*)aNotification{
   NSDictionary* info = [aNotification userInfo];
   keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
 }

-(void)keyboardDidHide:(NSNotification*)aNotification{
   [self restoreViewFrameOrigionYToZero];// keyboard is dismissed, restore frame view to its  zero origin
}
@end

스위프트 4

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(getInfo(notif:)), name: .UIKeyboardDidShow , object: nil)
}

그리고:

@objc func getInfo(notif: NSNotification) -> Void {  
    guard let userInfo = notif.userInfo else {return}

    if let myData = userInfo["UIKeyboardFrameBeginUserInfoKey"] as? CGRect {
        print(myData.width)
        print(myData.height)
    }
}

참고 URL : https://stackoverflow.com/questions/3546571/how-to-get-uikeyboard-size-with-ios

반응형