iOS/Objective-C

Objective-C) Keyboard Layout 감지

Brad_Heo 2024. 5. 30. 15:07

핸드폰의 특성상 타이핑을 해서 데이터를 입력할 일이 많습니다.

사용자들은 정보를 입력하기 위해서 핸드폰 스크린을 터치 하고 키보드를 타이핑 합니다.

만약 데이터를 입력하기 위해 터치를 했지만 키보드는 나오고, 데이터를 입력할 입력란이 키보드에 가려 안보인다면 당황하겠죠?

Objective-C 에선 어떻게 해결하는지 알아봅시다.

먼저 키보드가 나오는 이벤트를 받아야 합니다.

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

Notification을 이용해 키보드가 나타나면 showKeyboard 함수가 실행될 겁니다.

그러면showKeyboard 함수를 구현해봅시다.

- (void)showKeyboard:(NSNotification *)notification {
    _contentViewTop.constant = -HRATIO_SIZE(200);
    [UIView animateWithDuration:0.5f animations:^{
        [selfview.layoutIfNeeded];
    }];
}

생각보다 간단합니다. contentViewTopconstant를 200만큼 올립니다.
그리고 애니메이션을 추가해줘서 UX적으로 어색하지 않게 구현을 했습니다.

여기서 중요한건 contentViewTop은 storyboard의 View Constraints 입니다.
키보드가 올라왔을 때 올려줄 View의 Constraints을 설정하는 거죠!

스크린샷 2024-05-30 오후 3 02 02
@property (weak, nonatomic) IBOutlet NSLayoutConstraint      *contentViewTop;

그럼 키보드가 사라졌을 떄 화면을 다시 돌려놔야 겠죠?

동일하게 키보드가 내려갔을 떄 이벤트를 감지할 수 있습니다.

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

함수 호출은 다음과 같이 하면 됩니다.

- (void)hideKeyboard:(NSNotification *)notification {
    _contentViewTop.constant = 0;
    [UIView animateWithDuration:0.5f animations:^{
        [selfview.layoutIfNeeded];
    }];
}

constant를 다시 0으로 설정이 끝입니다.

감사합니다.

참고자료

https://stackoverflow.com/questions/29991246/set-constraints-through-code-to-an-element-from-storyboard-with-swift-ios8

'iOS > Objective-C' 카테고리의 다른 글

Objective-C) 생체인증타입 확인  (0) 2024.06.21
Objective-C) 클래스 객체함수 호출하기  (0) 2024.06.20
Objective-C) 캡쳐방지  (0) 2024.06.19
Objective-C) UIView 맨 앞으로 이동  (0) 2024.05.20