2014-11-05 1 views
0

텍스트 필드가있는 테이블 뷰가 있습니다. 텍스트 필드에 텍스트를 입력 할 때 텍스트 필드가 자동으로 위쪽으로 키보드 바로 위로 이동해야합니다.자동으로 구현 클래스의 로직을 사용하지 않고 텍스트 필드를 위로 스크롤합니다.

나는 텍스트 필드 대리자 메서드에서 논리를 쓰는 stackoverflow에서 많은 솔루션을 보았습니다.

로직없이 키보드 위의 텍스트 필드를 이동시키기위한 해결책을 공유하고 싶습니다.

이 게시물은 모두에게 해결책을 공유하는 것입니다.

이 솔루션은 'How to make a UITextField move up when keyboard is present?'미리

덕분에이 같은 동일하지 않습니다.

+3

어떻게 더 논리있을 수 없다 : 당신의 (a xib 또는 storyboard에, 나는 UIScrollView을 사용하고이 경우)를 설정하는 방법 UIViewController 서브 클래스에서

이 무엇입니까? 뭔가 텍스트 필드를 이동하려면보기를 스크롤하는 방법을 알고 있어야합니다. – rmaddy

+0

로직이 customtableviewcell에 있고 구현 된 클래스에서 동일한 대리자가 실행됩니다. –

+0

시도해보십시오 (https://github.com/michaeltyson/TPKeyboardAvoiding). 어쩌면 이것이 당신을 도울 것입니다. –

답변

0

아래 customcell //.h 파일을 제출하는

#import <UIKit/UIKit.h> 
@protocol TextFieldScrollToVisibleDelegate 
@optional 
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; 
- (void)textFieldDidBeginEditing:(UITextField *)textField; 
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField; 
- (void)textFieldDidEndEditing:(UITextField *)textField; 
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; 
- (BOOL)textFieldShouldClear:(UITextField *)textField; 
- (BOOL)textFieldShouldReturn:(UITextField *)textField; 


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView; 
- (BOOL)textViewShouldEndEditing:(UITextView *)textView; 

- (void)textViewDidBeginEditing:(UITextView *)textView; 
- (void)textViewDidEndEditing:(UITextView *)textView; 

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; 
- (void)textViewDidChange:(UITextView *)textView; 

- (void)textViewDidChangeSelection:(UITextView *)textView; 

@end 
@interface CustomTableViewCell : UITableViewCell <UITextFieldDelegate,UITextViewDelegate> 
@property (nonatomic, assign) NSObject <TextFieldScrollToVisibleDelegate> *mTextFieldScrollToVisibleDelegate_; 
@property (nonatomic) int paddingabovekeyboard; 
@end 

//.m 파일

#import "CustomTableViewCell.h" 
@interface CustomTableViewCell() 
@property (nonatomic)int keyboardHeight; 
@property (nonatomic)BOOL useSecondMode; 
@property (nonatomic)int actualViewHeight; 
@property (nonatomic)int actualViewWidth; 
@property (nonatomic)int previousYposition; 
@end 
#define kKeyboardHeightValue (keyboardHeight==0)?250:keyboardHeight 
@implementation CustomTableViewCell 
@synthesize mTextFieldScrollToVisibleDelegate_; 
@synthesize paddingabovekeyboard; 

@synthesize keyboardHeight; 
@synthesize useSecondMode; 
@synthesize actualViewHeight; 
@synthesize actualViewWidth; 
@synthesize previousYposition; 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     // Initialization code 
     paddingabovekeyboard=50; 
    } 
    return self; 
} 
-(void)wheatherFirstModeOrsecondMode { 
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; 
    BOOL statusBarHidden = [UIApplication sharedApplication].statusBarHidden; 
    int statusHight= 20; 
    if(statusBarHidden) { 
     statusHight=0; 
    } 
    int navheight=0; 
    id nav = [UIApplication sharedApplication].keyWindow.rootViewController; 
    if ([nav isKindOfClass:[UINavigationController class]]) { 
     UINavigationController *navc = (UINavigationController *) nav; 
     if(!navc.navigationBarHidden) { 
      navheight=44; 
     } 
    } 
    if(UI_USER_INTERFACE_IDIOM() ==UIUserInterfaceIdiomPhone) 
    { 
     if(orientation == 0||orientation == UIInterfaceOrientationPortrait) { 
      keyboardHeight = 216+paddingabovekeyboard; //44 
      actualViewHeight= [[UIScreen mainScreen]bounds].size.height-statusHight-navheight; 
      actualViewWidth =[[UIScreen mainScreen]bounds].size.width; 
     } else if(orientation == UIInterfaceOrientationLandscapeLeft||orientation == UIInterfaceOrientationLandscapeRight) { 
      keyboardHeight = 162+paddingabovekeyboard; //444 
      actualViewHeight= [[UIScreen mainScreen]bounds].size.width-statusHight-navheight; 
      actualViewWidth =[[UIScreen mainScreen]bounds].size.height; 
     } 
    } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){ 
     if(orientation == 0||orientation == UIInterfaceOrientationPortrait) { 
      keyboardHeight = 264+paddingabovekeyboard; //44 
      actualViewHeight= [[UIScreen mainScreen]bounds].size.height-statusHight-navheight; 
      actualViewWidth =[[UIScreen mainScreen]bounds].size.width; 

     } else if(orientation == UIInterfaceOrientationLandscapeLeft||orientation == UIInterfaceOrientationLandscapeRight) { 
      keyboardHeight = 352+paddingabovekeyboard;//44 
      actualViewHeight= [[UIScreen mainScreen]bounds].size.width-statusHight-navheight; 
      actualViewWidth =[[UIScreen mainScreen]bounds].size.height; 

     } 
    } 
    UITableView *myTableView = (UITableView *)[self superview]; 
    if(![myTableView isKindOfClass:[UITableView class]]) { 
     myTableView = (UITableView *)[[self superview] superview]; 
    } 
    if(![myTableView isKindOfClass:[UITableView class]]) { 
     myTableView = (UITableView *)[[[self superview] superview] superview]; 
    } 
    NSLog(@"keyboardHeight %dactualViewHeight%d",keyboardHeight,actualViewHeight); 
    if(myTableView.frame.origin.y>actualViewHeight-keyboardHeight-50) { 
     useSecondMode=TRUE; 
    } else { 
     useSecondMode=FALSE; 
    } 
#undef kKeyboardHeightValue 
#define kKeyboardHeightValue (keyboardHeight==0)?250:keyboardHeight 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 
- (void)textFieldDidBeginEditing:(UITextField *)textField { 
    @try { 
     UITableView *myTableView = (UITableView *)[self superview]; 
     if(![myTableView isKindOfClass:[UITableView class]]) { 
      myTableView = (UITableView *)[[self superview] superview]; 
     } 
     if(![myTableView isKindOfClass:[UITableView class]]) { 
      myTableView = (UITableView *)[[[self superview] superview] superview]; 
     } 
     int scrollpadding; 
     if(!self.useSecondMode) { 
      scrollpadding=actualViewHeight - (myTableView.frame.origin.y+myTableView.frame.size.height); 
      scrollpadding = kKeyboardHeightValue-scrollpadding; 
     } else { 
      CGRect lframe= myTableView.superview.frame; 
      self.previousYposition=myTableView.superview.frame.origin.y; 

      int heighttochange=0; 
      if(myTableView.frame.origin.y<myTableView.frame.size.height) { 
       heighttochange = myTableView.frame.size.height; 
      } else { 
       heighttochange = myTableView.frame.origin.y; 

      } 
      int temp = actualViewHeight- keyboardHeight; 
      temp = self.frame.origin.y - temp+50; 
      heighttochange = (heighttochange>temp)?temp:heighttochange; 
      lframe.origin.y-=heighttochange; 
      self.superview.frame=lframe; 

      scrollpadding =actualViewHeight - ((myTableView.frame.origin.y+lframe.origin.y)+myTableView.frame.size.height); 
      scrollpadding = kKeyboardHeightValue-scrollpadding; 
     } 

     UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, scrollpadding, 0.0); 
     myTableView.contentInset = contentInsets; 
     myTableView.scrollIndicatorInsets = contentInsets; 
     CGRect lFrame=[myTableView convertRect:textField.bounds fromView:textField]; 
     [myTableView scrollRectToVisible:lFrame animated:NO]; 

     if (nil != mTextFieldScrollToVisibleDelegate_ && [mTextFieldScrollToVisibleDelegate_ respondsToSelector:@selector(textFieldDidBeginEditing:)]) { 
      [mTextFieldScrollToVisibleDelegate_ textFieldDidBeginEditing:textField]; 
     } 
    } 
    @catch (NSException *exception) { 
    } 
    @finally { 
    } 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField { 
    @try { 
     UITableView *myTableView = (UITableView *)[self superview]; 
     if(![myTableView isKindOfClass:[UITableView class]]) { 
      myTableView = (UITableView *)[[self superview] superview]; 
     } 
     if(![myTableView isKindOfClass:[UITableView class]]) { 
      myTableView = (UITableView *)[[[self superview] superview] superview]; 
     } 

     if(!useSecondMode) { 
      UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
      myTableView.contentInset = contentInsets; 
      myTableView.scrollIndicatorInsets = contentInsets; 
     } else { 
      CGRect lframe= self.superview.frame; 
      lframe.origin.y=self.previousYposition; 
      self.superview.frame=lframe; 
      UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
      myTableView.contentInset = contentInsets; 
      myTableView.scrollIndicatorInsets = contentInsets; 
     } 
     if (nil != mTextFieldScrollToVisibleDelegate_ && [mTextFieldScrollToVisibleDelegate_ respondsToSelector:@selector(textFieldDidEndEditing:)]) { 
      [mTextFieldScrollToVisibleDelegate_ textFieldDidEndEditing:textField]; 
     } 
    } 
    @catch (NSException *exception) { 
    } 
    @finally { 
    } 
} 

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    @try { 
     UITableView *myTableView = (UITableView *)[self superview]; 
     if(![myTableView isKindOfClass:[UITableView class]]) { 
      myTableView = (UITableView *)[[self superview] superview]; 
     } 
     if(![myTableView isKindOfClass:[UITableView class]]) { 
      myTableView = (UITableView *)[[[self superview] superview] superview]; 
     } 
     UITableViewCell *cell =((UITableViewCell*)[[textField superview] superview]); 
     if(![cell isKindOfClass:[UITableViewCell class]]) { 
      cell = (UITableViewCell *)[[[textField superview]superview] superview]; 
     } 
     if(!useSecondMode) { 
      UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
      myTableView.contentInset = contentInsets; 
      myTableView.scrollIndicatorInsets = contentInsets; 
     } else { 
      CGRect lframe= self.superview.frame; 
      lframe.origin.y=self.previousYposition; 
      self.superview.frame=lframe; 
      UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
      myTableView.contentInset = contentInsets; 
      myTableView.scrollIndicatorInsets = contentInsets; 
     } 
     [textField resignFirstResponder]; 

     if (nil != mTextFieldScrollToVisibleDelegate_ && [mTextFieldScrollToVisibleDelegate_ respondsToSelector:@selector(textFieldShouldReturn:)]) { 
      return [mTextFieldScrollToVisibleDelegate_ textFieldShouldReturn:textField]; 
     } 
     return YES; 
    } 
    @catch (NSException *exception) { 
    } 
    @finally { 
    } 
} 

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { 
    if (nil != mTextFieldScrollToVisibleDelegate_ && [mTextFieldScrollToVisibleDelegate_ respondsToSelector:@selector(textFieldShouldEndEditing:)]) { 
     return [mTextFieldScrollToVisibleDelegate_ textFieldShouldEndEditing:textField]; 
    } 
    return YES; 
} 

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ 
    [self wheatherFirstModeOrsecondMode]; 

    if (nil != mTextFieldScrollToVisibleDelegate_ && [mTextFieldScrollToVisibleDelegate_ respondsToSelector:@selector(textFieldShouldBeginEditing:)]) { 
     return [mTextFieldScrollToVisibleDelegate_ textFieldShouldBeginEditing:textField]; 
    } 
    return YES; 
} 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    if (nil != mTextFieldScrollToVisibleDelegate_ && [mTextFieldScrollToVisibleDelegate_ respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) { 
     return [mTextFieldScrollToVisibleDelegate_ textField:textField shouldChangeCharactersInRange:range replacementString:string]; 
    } 
    return YES; 
} 

@end 

프로젝트

에 지금을 위의 두 사용자 정의 셀 파일을 추가합니다 아래는 구현 방법입니다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
     UITextField *ltext = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 120, 30)]; 
     ltext.borderStyle = UITextBorderStyleLine; 
     ltext.delegate=cell; 
     cell.mTextFieldScrollToVisibleDelegate_=self; 
     ltext.tag=1; 
     [cell.contentView addSubview:ltext]; 

    } 
    cell.paddingabovekeyboard=44; 

    return cell; 
} 

위의 코드에 대한 설명 UITableViewCell 대신 CustomTableViewCell을 사용하십시오.

참고 :이 코드는 내가 당신의 UITextField 대리자 메서드를 묶어하지 않는, LHSKeyboardAdjusting을 사용하는있는 tableview

+3

그것은 많은 논리입니다. 귀하의 질문에 논리가 없다는 결론을 얻었습니다. – rmaddy

+0

구현 클래스에서 텍스트 필드 대리자에는 논리가 없습니다. –

2

만 텍스트 필드에 적용됩니다. -[UITextFieldDelegate textFieldShouldReturn:]이 (가) 해고되면 다음 텍스트 필드로 넘어갈 수 없도록 많은 라이브러리가 대리인을 인수합니다.

LHSKeyboardAdjusting은 키보드 표시/숨기기 이벤트를 수신하고 전달하는보기의 하단 제한을 조정합니다. 멋진 것은 UIViewUIScrollView과 작동합니다.

#import "UIViewControllerSubclass.h" 
#import <LHSKeyboardAdjusting/UIViewController+LHSKeyboardAdjustment.h> 

@interface UIViewControllerSubclass() <LHSKeyboardAdjusting> 

@property (nonatomic, weak) IBOutlet UIScrollView *scrollView; 

/** The constraint that anchors '_scrollView' bottom to '_view' bottom */ 
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *scrollViewBottomConstraint; 

@end 

@implementation UIViewControllerSubclass 

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    [self lhs_activateKeyboardAdjustment]; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 

    [self lhs_deactivateKeyboardAdjustment]; 
} 

#pragma mark - LHSKeyboardAdjusting 

- (NSLayoutConstraint *)keyboardAdjustingBottomConstraint { 
    return self.scrollViewBottomConstraint; 
} 

@end 
관련 문제