如何在目标c中出现键盘时滚动视图?

时间:2012-01-25 12:32:53

标签: objective-c ios keyboard scroll

我尝试了这个但是视图太小而无法向上滚动。如何滚动更多?

// 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);
scroll.contentInset = contentInsets;
scroll.scrollIndicatorInsets = contentInsets;

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

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

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
EPostaText = textField;

}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
EPostaText = nil;
}

3 个答案:

答案 0 :(得分:2)

最好的方法 - 将滚动视图容器的大小调整为可见区域并使用:

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated

答案 1 :(得分:0)

自从我找到它之后,我使用了TPKeyboardAvoiding

效果很好,设置非常简单:

  1. 将UIScrollView添加到视图控制器的xib
  2. 将滚动视图的类设置为TPKeyboardAvoidingScrollView(仍然是 在xib,通过身份检查员)
  3. 将所有控件放在该滚动视图中
  4. 祝你好运!

答案 2 :(得分:0)

这是我的代码,希望它能帮到你。如果您有许多文本字段

,它可以正常工作
CGPoint contentOffset;
bool isScroll;
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    contentOffset = self.myScroll.contentOffset;
    CGPoint newOffset;
    newOffset.x = contentOffset.x;
    newOffset.y = contentOffset.y;
    //check push return in keyboar
    if(!isScroll){
        //180 is height of keyboar
        newOffset.y += 180;
        isScroll=YES;
    }
   [self.myScroll setContentOffset:newOffset animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //reset offset of content
    isScroll = NO;
    [self.myScroll setContentOffset:contentOffset animated:YES];
    [textField endEditing:true];
    return  true;
}