키보드가 있을 때 편집 시작 시 UITextField를 위로 이동하려면 어떻게 해야 합니까?
iOS SDK의 경우:
는 나나 a a a가 있다UIView
UITextField
키보드를 기동합니다.을 사용하다
수 .
UIScrollView
를 볼 수.자동으로 "점프" 또는 단축
는 가가 a 가 하다는 것을 알고 있다.UIScrollView
제 반을 바꾸려고 해봤어요UIView
a까지UIScrollView
텍스트 상자를 위아래로 스크롤할 수 없습니다.
다 요?UIView
a. a. a.UIScrollView
른른른른른른른른른른른른른?
활성 텍스트 필드로 자동 스크롤하려면 무엇이 구현되어야 합니까?
컴포넌트의 셋업은 가능한 한 인터페이스 빌더로 실시하는 것이 이상적입니다.필요한 것만 코드를 쓰고 싶어요.
★★★★★UIView
(오류)UIScrollView
하고 있는 )는에 의해 UITabBar
이치노
키보드가 뜨는 때를 위해 스크롤 바를 추가합니다.필수는 아니지만, 예를 들어 사용자가 텍스트 상자를 스크롤하거나 변경할 수 있기 때문에 더 나은 인터페이스를 제공할 수 있다고 생각합니다.
UIScrollView
이렇게사용하고 있는 것은 다음과 같습니다.
-(void)textFieldDidBeginEditing:(UITextField *)textField {
//Keyboard becomes visible
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height - 215 + 50); // Resize
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
// Keyboard will hide
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height + 215 - 50); // Resize
}
다만, 이 조작으로 자동적으로 「위로 이동」하거나, 아래 텍스트 필드가 표시되는 영역의 중앙에 배치되는 일은 없습니다.이것이 제가 정말로 하고 싶은 일입니다.
은 「○○○○○○○○○○○○만 있으면 됩니다.
ScrollView
를 [/FONT CHANGE글꼴 변경:글꼴 변경:>)ScrollView
의 로서 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★TextField
키보드가 뜨면 위로 스크롤 할 필요가 없습니다.)「 」를 인 방법
TextField
는 키보드로 가려지지 않고 키보드가 표시될 때마다 화면을 위/아래로 이동합니다.
다음은 샘플 코드입니다.
#define kOFFSET_FOR_KEYBOARD 80.0
-(void)keyboardWillShow {
// Animate the current view out of the way
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
-(void)keyboardWillHide {
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
if ([sender isEqual:mailTf])
{
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
}
}
//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // if you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
}
else
{
// revert back to the normal state.
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;
[UIView commitAnimations];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// register for keyboard notifications
[[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];
// unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
또 다른 문제들도 많이 있었습니다.UIScrollView
개의 수 of의 UITextFields
그 중 하나 또는 여러 개가 편집 중에 키보드에 의해 가려집니다.
에서는 만약 이 이 일을 할 때 해야 할 이 몇 가지 있습니다.UIScrollView
제대로 스크롤되지 않습니다.
가 1) content Size content content Size content content size size 1 the the 1 the the the the the the the보다 합니다.UIScrollView
이해 UIScrollViews
'그거'야?UIScrollView
「 content Size 」(콘텐츠 사이즈). ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★UIScrollview
위치로 가 contentSize보다 .UIScrollView
"콘텐츠 크기" "콘텐츠 크기" "콘텐츠 크기" "콘텐츠 크기" " 크기" = " " 콘텐츠사이즈 = "BTW", "콘텐츠 사이즈" =CGSizeZero
.
2) 이제 이해하셨으니UIScrollView
「의 가 자신의 를 가리는 일이 할 수 방법입니다.UIScrollView's
'아까 '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '', '아까', '아까' 크기를UIScrollView
때 'Keyboard'를 사용할 수 .UIScrollView
만 있는 창UIScrollView
frame를 뺀 입니다.이렇게 하면 창이 보기 쉬운 작은 영역만 표시됩니다.
3) 여기 단점이 있습니다.이했을 때, 저는 이 기능을 했습니다.CGRect
와 콜 " " " 입니다.UIScrollView's
methodscrollRecToVisible.이 기능을 구현했습니다.UITextFieldDelegate
법 methodtextFieldDidBeginEditing
의 ,scrollRecToVisible
방법.이것은 실제로 이상한 부작용과 함께 작동하여 스크롤이 스냅될 수 있습니다.UITextField
자자걸음음하하하하하오랫동안 나는 그것이 무엇인지 알 수 없었다. 다음에 제가 요.textFieldDidBeginEditing
이 통한다고 해서 저는 '아, 아, 아, 아, 아, 아, 아, 아, 아.UIScrollView
되어 있는 「편집중」을 .UITextField
눈에 보이는 창으로 암묵적으로 들어갑니다.★★★의 UITextFieldDelegate
및 을 합니다.scrollRecToVisible
불필요한 것이었고 이상한 부작용의 원인이었습니다.
, 을 하기 위한 입니다.UITextField
in a a a a UIScrollView
키보드가 뜨면 제자리에 놓입니다.
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:self.view.window];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:self.view.window];
keyboardIsShown = NO;
//make contentSize bigger than your scrollSize (you will need to figure out for your own use case)
CGSize scrollContentSize = CGSizeMake(320, 345);
self.scrollView.contentSize = scrollContentSize;
}
- (void)keyboardWillHide:(NSNotification *)n
{
NSDictionary* userInfo = [n userInfo];
// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
// resize the scrollview
CGRect viewFrame = self.scrollView.frame;
// I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
viewFrame.size.height += (keyboardSize.height - kTabBarHeight);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[self.scrollView setFrame:viewFrame];
[UIView commitAnimations];
keyboardIsShown = NO;
}
- (void)keyboardWillShow:(NSNotification *)n
{
// This is an ivar I'm using to ensure that we do not do the frame size adjustment on the `UIScrollView` if the keyboard is already shown. This can happen if the user, after fixing editing a `UITextField`, scrolls the resized `UIScrollView` to another `UITextField` and attempts to edit the next `UITextField`. If we were to resize the `UIScrollView` again, it would be disastrous. NOTE: The keyboard notification will fire even when the keyboard is already shown.
if (keyboardIsShown) {
return;
}
NSDictionary* userInfo = [n userInfo];
// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
// resize the noteView
CGRect viewFrame = self.scrollView.frame;
// I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
viewFrame.size.height -= (keyboardSize.height - kTabBarHeight);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[self.scrollView setFrame:viewFrame];
[UIView commitAnimations];
keyboardIsShown = YES;
}
- 하려면 다음 사이트를 방문하십시오.
viewDidLoad
- 을 해제합니다( 「 」 ).
viewDidUnload
- 확인하세요.
contentSize
, 그 입니다.UIScrollView
viewDidLoad
- 축소
UIScrollView
- 를 원래대로 되돌리다
UIScrollView
키보드를 사용할 수 없습니다. - 알림이 ivar로 를 사용하여 합니다.
UITextField
키보드가 이미 있는 경우에도 탭이 되어 있기 때문에,UIScrollView
이미 줄어들었을 때
가지 은 이 '이것'은UIKeyboardWillShowNotification
에 표시되어 됩니다.UITextField
이ararar 를 사용하여 했습니다.UIScrollView
키보드가 이미 화면에 표시되어 있는 경우.「」의 .UIScrollView
키보드가 이미 있으면 큰일 날 거예요!
이 코드가 여러분 중 몇 분의 두통을 덜어주길 바랍니다.
실제로 Apple의 실장을 사용하는 것이 가장 좋습니다(문서 참조).그러나 그들이 제공하는 코드는 결함이 있습니다.에 기재되어 있는 부분을 교환해 주세요.keyboardWasShown:
다음에 대한 코멘트 바로 아래에 기재되어 있습니다.
NSDictionary* info = [aNotification userInfo];
CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view];
CGSize kbSize =keyPadFrame.size;
CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview];
CGRect aRect = self.view.bounds;
aRect.size.height -= (kbSize.height);
CGPoint origin = activeRect.origin;
origin.y -= backScrollView.contentOffset.y;
if (!CGRectContainsPoint(aRect, origin)) {
CGPoint scrollPoint = CGPointMake(0.0,CGRectGetMaxY(activeRect)-(aRect.size.height));
[backScrollView setContentOffset:scrollPoint animated:YES];
}
(1) 내에 의 프레임입니다. (1) Apple의 코드입니다.ScrollView
따라서 이미 스크롤되어 있을 수 있으므로 오프셋을 고려해야 합니다.
origin.y -= scrollView.contentOffset.y
(2의 높이에 2) contentOffset, contentOffset, contentOffset, contentOffset, contentOffset, contentOffset, contentOffset을 시키고 싶습니다.contentOffset
화면에 표시되는 높이가 아닌 높이로 표시됩니다.
activeField.frame.origin.y-(aRect.size.height)
»textFieldDidBeginEditting
및에textFieldDidEndEditing
를 [self animateTextField:textField up:YES]
다음과 같이 합니다.
-(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 = -130; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? movementDistance : -movementDistance);
[UIView beginAnimations: @"animateTextField" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
이 코드가 도움이 되길 바랍니다.
스위프트 5
func animateTextField(textField: UITextField, up: Bool) {
let movementDistance: CGFloat = -130
let movementDuration: Double = 0.3
var movement:CGFloat = 0
if up {
movement = movementDistance
} else {
movement = -movementDistance
}
UIView.animate(withDuration: movementDuration, delay: 0, options: [.beginFromCurrentState]) {
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
animateTextField(textField: textField, up: true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
animateTextField(textField: textField, up: false)
}
TextFields 사용만:
사용1a) ★★Interface Builder
: [ Fields = ]> [ Edit = ]> [ In = ]> [ ] : [ All Text Fields = ]> [ Edit ]> [ Embed In = ]> [ Scroll View ]를
1b) ScrollView라고 하는 UIScrollView에 TextFields를 수동으로 삽입한다.
2) ★★UITextFieldDelegate
3) 을 설정합니다.textField.delegate = self;
(하다)Interface Builder
)
4) 복사/붙여넣기:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
CGPoint scrollPoint = CGPointMake(0, textField.frame.origin.y);
[scrollView setContentOffset:scrollPoint animated:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[scrollView setContentOffset:CGPointZero animated:YES];
}
Universal Solution에서는 IQKeyboard Manager를 구현하기 위한 접근방식을 설명했습니다.
스텝 1: - 글로벌 알림을 추가했습니다.UITextField
,UITextView
, , , , 입니다.UIKeyboard
싱글톤급에서.IQKeyboard Manager라고 부릅니다.
순서 2:- 발견된 경우UIKeyboardWillShowNotification
,UITextFieldTextDidBeginEditingNotification
★★★★★★★★★★★★★★★★★」UITextViewTextDidBeginEditingNotification
, , 알림, 알림, 알림, .topMostViewController
의 UIWindow.rootViewController
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★UITextField
/UITextView
위에, on그 on ontopMostViewController.view
의 프레임을 조정할 필요가 있습니다.
스텝 3: - 예상 이동 거리를 계산했습니다.topMostViewController.view
회답에 UITextField
/UITextView
.
순서 4:- 이동했습니다.topMostViewController.view.frame
예상 이동 거리에 따라 위/아래로 이동합니다.
순서 5:- 발견된 경우UIKeyboardWillHideNotification
,UITextFieldTextDidEndEditingNotification
★★★★★★★★★★★★★★★★★」UITextViewTextDidEndEditingNotification
한 번 , 알림, 알림, 알림, 알림.topMostViewController
의 UIWindow.rootViewController
★★★★★★ 。
스텝 6: - 교란된 거리 계산topMostViewController.view
원래 위치로 복구해야 합니다.
순서 7:-복원했습니다.topMostViewController.view.frame
방해된 거리에 따라 내려갑니다.
스텝 8: 앱 로드 시 싱글톤 IQKeyboard Manager 클래스의 인스턴스를 인스턴스화했기 때문에UITextField
/UITextView
예상 이동 거리에 따라 자동으로 조정됩니다.
코드 라인 없이 IQKeyboard Manager가 할 수 있는 것은 이것뿐입니다!!프로젝트에 관련된 소스 파일을 끌어다 놓기만 하면 됩니다.IQKeyboard Manager는 디바이스 오리엔테이션, 자동 UIToolbar 관리, Keyboard Distance From TextField 등을 지원합니다.
UIScrollView
,UITableView
그리고 심지어UICollectionView
서브클래스의 모든 텍스트필드를 키보드로 이동합니다.
키보드가 나타나려고 하면 서브클래스는 편집하려는 서브뷰를 찾아 키보드 팝업과 일치하는 애니메이션을 사용하여 해당 뷰가 표시되도록 프레임과 콘텐츠 오프셋을 조정합니다.키보드가 사라지면 이전 크기로 돌아갑니다.
으로는 어떤에서도 동작합니다.UITableView
- interface
여기: 텍스트 필드를 키보드로 이동하기 위한 솔루션
Swift 프로그래머의 경우:
할 수 을 뷰 , 「이러다」를 주세요.이러한 기능을 뷰 컨트롤러 클래스에 배치하고,UITextFieldDelegate
에 접속하여 textField의 를 textField로 합니다.self
textField.delegate = self // Setting delegate of your UITextField to self
위임 콜백 방식을 구현합니다.
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 100)
}
// Lifting the view up
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.3
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
Swift 4, 4.2, 5의 경우: 변경
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
로.
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
이 구현에 관한 마지막 주의사항:키보드가 표시된 상태에서 다른 뷰 컨트롤러를 스택에 푸시하면 뷰가 중앙 프레임으로 돌아가지만 키보드 오프셋이 재설정되지 않는 오류가 발생합니다.예를 들어 키보드가 nameField의 첫 번째 응답자이지만 Help View Controller를 스택에 푸시하는 버튼을 누르면 됩니다.오프셋 오류를 수정하려면 뷰 컨트롤러를 떠나기 전에 nameField.resignFirstResponder()를 호출하고 textFieldDidEndEditing 위임 메서드도 호출해야 합니다.이 작업은 viewWillDisplay 메서드로 수행합니다.
"네티즌", "네티즌", "네티즌", "네티즌", "네티즌", "", "", "네티즌", "네티즌", "네티즌", "네티즌", "
솔루션을 공유하겠습니다.
되어 있는 )UIKeyboardWill(Show|Hide)Notification
)
// Called when UIKeyboardWillShowNotification is sent
- (void)keyboardWillShow:(NSNotification*)notification
{
// if we have no view or are not visible in any window, we don't care
if (!self.isViewLoaded || !self.view.window) {
return;
}
NSDictionary *userInfo = [notification userInfo];
CGRect keyboardFrameInWindow;
[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrameInWindow];
// the keyboard frame is specified in window-level coordinates. this calculates the frame as if it were a subview of our view, making it a sibling of the scroll view
CGRect keyboardFrameInView = [self.view convertRect:keyboardFrameInWindow fromView:nil];
CGRect scrollViewKeyboardIntersection = CGRectIntersection(_scrollView.frame, keyboardFrameInView);
UIEdgeInsets newContentInsets = UIEdgeInsetsMake(0, 0, scrollViewKeyboardIntersection.size.height, 0);
// this is an old animation method, but the only one that retains compaitiblity between parameters (duration, curve) and the values contained in the userInfo-Dictionary.
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
_scrollView.contentInset = newContentInsets;
_scrollView.scrollIndicatorInsets = newContentInsets;
/*
* Depending on visual layout, _focusedControl should either be the input field (UITextField,..) or another element
* that should be visible, e.g. a purchase button below an amount text field
* it makes sense to set _focusedControl in delegates like -textFieldShouldBeginEditing: if you have multiple input fields
*/
if (_focusedControl) {
CGRect controlFrameInScrollView = [_scrollView convertRect:_focusedControl.bounds fromView:_focusedControl]; // if the control is a deep in the hierarchy below the scroll view, this will calculate the frame as if it were a direct subview
controlFrameInScrollView = CGRectInset(controlFrameInScrollView, 0, -10); // replace 10 with any nice visual offset between control and keyboard or control and top of the scroll view.
CGFloat controlVisualOffsetToTopOfScrollview = controlFrameInScrollView.origin.y - _scrollView.contentOffset.y;
CGFloat controlVisualBottom = controlVisualOffsetToTopOfScrollview + controlFrameInScrollView.size.height;
// this is the visible part of the scroll view that is not hidden by the keyboard
CGFloat scrollViewVisibleHeight = _scrollView.frame.size.height - scrollViewKeyboardIntersection.size.height;
if (controlVisualBottom > scrollViewVisibleHeight) { // check if the keyboard will hide the control in question
// scroll up until the control is in place
CGPoint newContentOffset = _scrollView.contentOffset;
newContentOffset.y += (controlVisualBottom - scrollViewVisibleHeight);
// make sure we don't set an impossible offset caused by the "nice visual offset"
// if a control is at the bottom of the scroll view, it will end up just above the keyboard to eliminate scrolling inconsistencies
newContentOffset.y = MIN(newContentOffset.y, _scrollView.contentSize.height - scrollViewVisibleHeight);
[_scrollView setContentOffset:newContentOffset animated:NO]; // animated:NO because we have created our own animation context around this code
} else if (controlFrameInScrollView.origin.y < _scrollView.contentOffset.y) {
// if the control is not fully visible, make it so (useful if the user taps on a partially visible input field
CGPoint newContentOffset = _scrollView.contentOffset;
newContentOffset.y = controlFrameInScrollView.origin.y;
[_scrollView setContentOffset:newContentOffset animated:NO]; // animated:NO because we have created our own animation context around this code
}
}
[UIView commitAnimations];
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillHide:(NSNotification*)notification
{
// if we have no view or are not visible in any window, we don't care
if (!self.isViewLoaded || !self.view.window) {
return;
}
NSDictionary *userInfo = notification.userInfo;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[[userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[[userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
// undo all that keyboardWillShow-magic
// the scroll view will adjust its contentOffset apropriately
_scrollView.contentInset = UIEdgeInsetsZero;
_scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
[UIView commitAnimations];
}
Shiun은 "알고 보니 UIScroll View는 실제로 암시적으로 현재 편집된 UITextField를 표시 가능한 창으로 가져온다고 생각한다"고 말했다.이것은 iOS 3.1.3에서는 해당되지만 3.2, 4.0, 4.1에서는 해당되지 않는 것 같다.iOS > = 3.2에서 UITextField를 표시하기 위해 명시적인 스크롤RectToVisible을 추가해야 했습니다.
가지 해야 할 은, 하는 입니다.UITextField
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★UITextFields
of UITableViewCells
.
약간의 추가 작업이 필요하지만 모든 데이터 입력 뷰의 테이블 뷰를 구현하는 것이 좋습니다.UITextView
your UITableViewCells
.
이 문서에서는 이 문제에 대한 해결책을 자세히 설명합니다.「키보드 아래에 있는 컨텐츠의 이동」아래의 소스 코드를 확인합니다.꽤 간단해.
편집: 예 edit edit edit edit edit edit edit edit edit edit edit edit edit edit edit 。 " " " " " " " 를 듣고 것입니다.UIKeyboardWillHideNotification
UIKeyboardDidHideNotification
그렇지 않으면 키보드 뒤에 있는 스크롤 뷰가 키보드의 애니메이션이 닫히는 동안 잘립니다.
가장 쉬운 솔루션 발견
- (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에서 사용할 수 있는 작은 수정:
#pragma mark UIKeyboard handling
#define kMin 150
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
if (currTextField) {
[currTextField release];
}
currTextField = [sender retain];
// Move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y + currTextField.frame.origin. y >= kMin) {
[self setViewMovedUp:YES];
}
}
// Method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // If you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y = kMin - currTextField.frame.origin.y ;
}
else
{
// Revert back to the normal state.
rect.origin.y = 0;
}
self.view.frame = rect;
[UIView commitAnimations];
}
- (void)keyboardWillShow:(NSNotification *)notif
{
// Keyboard will be shown now. Depending on which textfield is active, move up or move down the view appropriately
if ([currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y >= kMin)
{
[self setViewMovedUp:YES];
}
else if (![currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y < kMin)
{
[self setViewMovedUp:NO];
}
}
- (void)keyboardWillHide:(NSNotification *)notif
{
// Keyboard will be shown now. Depending on which textfield is active, move up or move down the view appropriately
if (self.view.frame.origin.y < 0 ) {
[self setViewMovedUp:NO];
}
}
- (void)viewWillAppear:(BOOL)animated
{
// Register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:self.view.window];
}
- (void)viewWillDisappear:(BOOL)animated
{
// Unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
RPDP의 코드가 텍스트필드를 키보드 밖으로 정상적으로 이동시킵니다.그러나 키보드를 사용 및 해제한 후 맨 위로 스크롤하면 맨 위가 보기 밖으로 스크롤됩니다.이는 시뮬레이터와 장치에 해당됩니다.보기 맨 위에 있는 내용을 읽으려면 보기를 다시 로드해야 합니다.
그의 다음 코드는 시야를 다시 어둡게 하는 거 아닌가요?
else
{
// revert back to the normal state.
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
원래 보기 상태로 되돌리려면 다음을 추가합니다.
-(void)textFieldDidEndEditing:(UITextField *)sender
{
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
뷰를 위로 이동시키는 것이 올바른 방법인지 잘 모르겠습니다.다른 방법으로 UIScroll View 크기를 조정했습니다.나는 작은 기사에서 그것을 자세히 설명했다.
이 짧은 속임수를 써 봐.
- (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 = textField.frame.origin.y / 2; // 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];
}
솔루션은 매우 많지만, 몇 시간이나 걸려야 제대로 작동합니다.이 코드를 여기에 넣습니다(프로젝트에 붙여넣기만 하면 수정은 불필요합니다).
@interface RegistrationViewController : UIViewController <UITextFieldDelegate>{
UITextField* activeField;
UIScrollView *scrollView;
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
//scrool view must be under main view - swap it
UIView* natView = self.view;
[self setView:scrollView];
[self.view addSubview:natView];
CGSize scrollViewContentSize = self.view.frame.size;
[scrollView setContentSize:scrollViewContentSize];
[self registerForKeyboardNotifications];
}
- (void)viewDidUnload {
activeField = nil;
scrollView = nil;
[self unregisterForKeyboardNotifications];
[super viewDidUnload];
}
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShown:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
-(void)unregisterForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
// unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)keyboardWillShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect frame = self.view.frame;
frame.size.height -= kbSize.height;
CGPoint fOrigin = activeField.frame.origin;
fOrigin.y -= scrollView.contentOffset.y;
fOrigin.y += activeField.frame.size.height;
if (!CGRectContainsPoint(frame, fOrigin) ) {
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y + activeField.frame.size.height - frame.size.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
[scrollView setContentOffset:CGPointZero animated:YES];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
추신: 코드를 통해 누군가가 원하는 효과를 빨리 얻을 수 있기를 바랍니다.(X코드 4.5)
@user271753
보기를 원래 추가 항목으로 되돌리려면:
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
[self setViewMovedUp:NO];
return YES;
}
뷰 프레임을 이동하기 위해 스크롤 뷰가 필요하지 않습니다. 수 요.viewcontroller's
첫 번째 응답자 텍스트 필드를 키보드 위에 배치할 수 있을 정도로 전체 보기가 위로 이동하도록 합니다. 때, 저는 인 when when다'를 .UIViewController
이렇게 하는 거야.키보드에 대한 알림이 표시되고 첫 번째 응답자 서브뷰가 검색되며 (필요한 경우) 첫 번째 응답자가 키보드 위에 오도록 메인뷰를 위쪽으로 애니메이션화합니다.키보드가 숨으면 원래 있던 곳으로 화면을 애니메이션으로 만듭니다.
이 서브클래스를 사용하려면 커스텀 뷰 컨트롤러를 GMKeyboard 서브클래스로 만듭니다.VC 및 VC는 이 기능을 상속합니다(실장하고 있는지 확인하세요).viewWillAppear
★★★★★★★★★★★★★★★★★」viewWillDisappear
슈퍼라고 불러야 한다).그 수업은 기투브에 있다.
Swift 4 입니다.
위아래로 할 수 .UITextField
★★★UIView
★★★★★★★★★★★★★★★★ UIKeyBoard
★★★★★★★★★★★★★★★★ Animation
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
@IBOutlet var chatView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
textField.resignFirstResponder()
}
@objc func keyboardWillChange(notification: NSNotification) {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
print("deltaY",deltaY)
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.chatView.frame.origin.y+=deltaY // Here You Can Change UIView To UITextField
},completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
여기 구체적인 레이아웃을 위해 제가 생각해낸 해킹 솔루션이 있습니다.이 솔루션은 Matt Gallagher 솔루션과 유사하며 단면을 스크롤하여 볼 수 있습니다.iPhone 개발은 아직 처음이라 레이아웃은 잘 모릅니다.그래서 이 해킹.
이 구현에서는 필드를 클릭할 때 스크롤을 지원하고 사용자가 키보드에서 다음을 선택할 때 스크롤을 지원해야 했습니다.
나는 키가 775인 체외수정을 했다.컨트롤은 기본적으로 3인 1조로 넓은 공간에 분산되어 있습니다.저는 다음과 같은 IB 레이아웃을 갖게 되었습니다.
UIView -> UIScrollView -> [UI Components]
여기 해킹이 있다
UIScrollView 높이를 실제 레이아웃(1250)보다 500 단위 크게 설정했습니다.그런 다음 스크롤해야 할 절대 위치를 가진 어레이를 만들고 IB 태그 번호를 기반으로 위치를 가져오는 간단한 기능을 만들었습니다.
static NSInteger stepRange[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 140, 140, 140, 140, 410
};
NSInteger getScrollPos(NSInteger i) {
if (i < TXT_FIELD_INDEX_MIN || i > TXT_FIELD_INDEX_MAX) {
return 0 ;
return stepRange[i] ;
}
이제 textFieldDidBeginEditing과 textFieldShouldReturn에서 다음 두 줄의 코드를 사용하면 됩니다(다음 필드 네비게이션을 작성하는 경우 후자 코드).
CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
예를 들면.
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
[nextResponder becomeFirstResponder];
CGPoint point = CGPointMake(0, getScrollPos(nextTag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
}
else{
[textField resignFirstResponder];
}
return YES ;
}
이 메서드는 다른 메서드와 달리 '롤백'되지 않습니다.이것은 필수가 아니었다.이번에도 꽤 '키 큰' UIView용이어서 내부 레이아웃 엔진을 배울 시간이 없었습니다.
문서에 따르면 iOS 3.0 현재UITableViewController
클래스는 텍스트 필드의 인라인 편집이 있을 때 테이블 뷰의 크기를 자동으로 조정하고 재배치합니다.텍스트 필드를 안에 넣는 것만으로는 충분하지 않다고 생각합니다.UITableViewCell
몇몇이 지적한 바와 같이
문서에서:
테이블 뷰 컨트롤러는 테이블 뷰 행의 인라인 편집을 지원합니다.예를 들어 행에 편집 모드에 텍스트필드가 포함되어 있는 경우 편집 중인 행을 표시되는 가상 키보드 위로 스크롤합니다.
여기서 키패드를 다룰 수 있는 가장 간단한 해결책을 찾았습니다.
샘플 코드 아래에 복사 붙여넣기를 하고 텍스트 필드 또는 위로 이동하려는 보기를 변경하기만 하면 됩니다.
순서 1
아래의 두 가지 방법으로 컨트롤러에 복사 붙여넣기만 하면 됩니다.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)deregisterFromKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
순서 2
키패드 알림을 viewWillAple 메서드와 viewWillDisplay 메서드에 각각 등록 및 등록 해제합니다.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self registerForKeyboardNotifications];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self deregisterFromKeyboardNotifications];
[super viewWillDisappear:animated];
}
스텝 3
소울 파트가 나타납니다. 텍스트 필드를 바꾸고 높이를 위쪽으로 이동합니다.
- (void)keyboardWasShown:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
CGSize currentKeyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
//you need replace your textfield instance here
CGPoint textFieldOrigin = self.tokenForPlaceField.frame.origin;
CGFloat textFieldHeight = self.tokenForPlaceField.frame.size.height;
CGRect visibleRect = self.view.frame;
visibleRect.size.height -= currentKeyboardSize.height;
if (!CGRectContainsPoint(visibleRect, textFieldOrigin))
{
//you can add yor desired height how much you want move keypad up, by replacing "textFieldHeight" below
CGPoint scrollPoint = CGPointMake(0.0, textFieldOrigin.y - visibleRect.size.height + textFieldHeight); //replace textFieldHeight to currentKeyboardSize.height, if you want to move up with more height
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillBeHidden:(NSNotification *)notification
{
[self.scrollView setContentOffset:CGPointZero animated:YES];
}
레퍼런스: 이 아름다운 코드 스냅과 깨끗한 솔루션을 공유해 주신 분께 감사드립니다.
이게 누군가에게 엄청나게 도움이 되었으면 좋겠다.
이 주제에 대해 초보자를 위한 좋은 튜토리얼을 찾다가 여기서 최고의 튜토리얼을 찾았습니다.
서서 MIScrollView.h
맨 예제는 .
@property (nonatomic, retain) id backgroundTapDelegate;
보시다시피.
UITextField
UITableViewCell
이치노
그렇지 않은 경우 테이블 뷰의 코드/설정이 잘못되었기 때문일 수 있습니다.
를 들어 긴 했을 때UITextField
같이 되어 있습니다.
-(void) viewWillAppear:(BOOL)animated
{
[self.tableview reloadData];
}
텍스트 필드 내부를 클릭했을 때 나타나는 키보드에 의해 하단에 있는 텍스트 필드가 가려졌습니다.
이걸 고치려면 이걸 해야 했어
-(void) viewWillAppear:(BOOL)animated
{
//add the following line to fix issue
[super viewWillAppear:animated];
[self.tableview reloadData];
}
한 줄도 쓸 필요가 없는 서드 파티 사용
https://github.com/hackiftekhar/IQKeyboardManager
앤 IQKeyboardManager
를 참조해 주세요.되면 을 .README
★★★★★★ 。
남자들은 키보드를 관리하는 것이 정말 골칫거리입니다.
주의: 이 답변은 textField가 스크롤 뷰에 있다고 가정합니다.
이 문제는 스크롤 콘텐츠를 사용하여 처리하는 것이 좋습니다.뷰의 프레임을 조작하지 않고, inset 및 scroll Content Offset 를 실행합니다.
먼저 키보드 알림을 듣겠습니다.
//call this from viewWillAppear
-(void)addKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
//call this from viewWillDisappear
-(void)removeKeyboardNotifications{
[[NSNotificationCenter default
Center] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
다음 단계에서는 현재 첫 번째 응답자를 나타내는 속성(현재 키보드를 가진 UITextfield/UITextVIew)을 유지합니다.
위임 메서드를 사용하여 이 속성을 설정합니다.다른 컴포넌트를 사용하고 있다면 비슷한 컴포넌트가 필요합니다.
텍스트 필드의 경우 didBeginEditing으로 설정하고 textView의 경우 shouldBeginEditing으로 설정합니다.어떤 이유로 인해 textViewDidBeginediting이 UIKeyboardWillShowNotification 뒤에 호출되기 때문입니다.
-(BOOL)textViewShouldBeginEditing:(UITextView * )textView{
self.currentFirstResponder = textView;
return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
self.currentFirstResponder = textField;
}
마지막으로, 여기 마법이 있다.
- (void)keyboardWillShow:(NSNotification*)aNotification{
NSDictionary* info = [aNotification userInfo];
CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
/*if currentFirstResponder is overlayed by the keyboard, move it so it bottom ends where the keyboard begins*/
if(self.currentFirstResponder){
//keyboard origin in currentFirstResponderFrame
CGPoint keyboardOrigin = [self.currentFirstResponder convertPoint:kbFrame.origin fromView:nil];
float spaceBetweenFirstResponderAndKeyboard = abs(self.currentFirstResponder.frame.size.height-keyboardOrigin.y);
//only scroll the scrollview if keyboard overlays the first responder
if(spaceBetweenFirstResponderAndKeyboard>0){
//if i call setContentOffset:animate:YES it behaves differently, not sure why
[UIView animateWithDuration:0.25 animations:^{
[self.scrollView setContentOffset:CGPointMake(0,self.scrollView.contentOffset.y+spaceBetweenFirstResponderAndKeyboard)];
}];
}
}
//set bottom inset to the keyboard height so you can still scroll the whole content
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
_scrollView.contentInset = contentInsets;
_scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)keyboardWillHide:(NSNotification*)aNotification{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_scrollView.contentInset = contentInsets;
_scrollView.scrollIndicatorInsets = contentInsets;
}
재빠르다
import UIKit
class ExampleViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var textField1: UITextField!
@IBOutlet var textField2: UITextField!
@IBOutlet var textField3: UITextField!
@IBOutlet var textField4: UITextField!
@IBOutlet var textField5: UITextField!
var activeTextField: UITextField!
// MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
self.textField1.delegate = self
self.textField2.delegate = self
self.textField3.delegate = self
self.textField4.delegate = self
self.textField5.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.registerForKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.unregisterFromKeyboardNotifications()
}
// MARK: - Keyboard
// Call this method somewhere in your view controller setup code.
func registerForKeyboardNotifications() {
let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
center.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
func unregisterFromKeyboardNotifications () {
let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
center.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
// Called when the UIKeyboardDidShowNotification is sent.
func keyboardWasShown (notification: NSNotification) {
let info : NSDictionary = notification.userInfo!
let kbSize = (info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue() as CGRect!).size
let contentInsets: UIEdgeInsets = 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.
var aRect = self.view.frame
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, self.activeTextField.frame.origin) ) {
self.scrollView.scrollRectToVisible(self.activeTextField.frame, animated: true)
}
}
// Called when the UIKeyboardWillHideNotification is sent
func keyboardWillBeHidden (notification: NSNotification) {
let contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
// MARK: - Text Field
func textFieldDidBeginEditing(textField: UITextField) {
self.activeTextField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
self.activeTextField = nil
}
}
언급URL : https://stackoverflow.com/questions/1126726/how-can-i-make-a-uitextfield-move-up-when-the-keyboard-is-present-on-starting
'programing' 카테고리의 다른 글
[](대괄호)의 [: 너무 많은 인수] 오류의 의미 (0) | 2023.04.23 |
---|---|
HTML을 일반 텍스트로 변환하려면 어떻게 해야 합니까? (0) | 2023.04.23 |
목록 내의 여러 data.frames를 동시에 Marge합니다. (0) | 2023.04.23 |
Swift에서 빈 어레이를 만드는 방법 (0) | 2023.04.23 |
What does >& mean? (0) | 2023.04.23 |