当键盘在文本字段上时,ios移动scrollview

时间:2013-11-27 03:56:38

标签: ios objective-c

拜托,你能纠正我的代码,所以我有一个简单的应用程序示例,文本字段在键盘结束时会向上移动吗?

我尝试使用来自ios开发人员库https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

的代码实现它

但我不知道他们的意思是“活动字段存储在自定义变量中(在此示例中称为activeField)”并且我可能做了其他错误。在viewWillAppear中使用registerForKeyboardNotifications是否可以?

我知道这个问题有一些线索,但我是新手,我很难理解它们。我不想只是学习如何,但为什么,这就是为什么我不想使用github其他建议等的现成解决方案。

我的代码atm:

·H:

#import <UIKit/UIKit.h>

@interface VNViewController : UIViewController<UIScrollViewDelegate, UITextFieldDelegate>

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

@end

的.m:

#import "VNViewController.h"

@interface VNViewController ()

@end


@implementation VNViewController

@synthesize scrollView;
@synthesize texticek;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 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);
    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.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
    }
}

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

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

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

@end

7 个答案:

答案 0 :(得分:31)

单击它时向上移动文本字段,请使用下面的代码。它只需要你的卷轴出口

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    self.scroll.contentOffset = CGPointMake(0, textField.frame.origin.y);
}

您可以通过减去y位置值(textfield.frame.origin.y - 某个值)来更改应显示的文本字段的位置

如果您想为滚动设置动画,可以这样做:

CGPoint newOffset = CGPointMake(0, textField.frame.origin.y-40);
[self.scroll setContentOffset: newOffset animated: YES];

答案 1 :(得分:10)

在ViewDidLoad中,注册通知:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

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

添加以下观察者方法,当键盘出现时自动滚动。

- (void)keyboardWasShown:(NSNotification*)notification
   {
        NSDictionary *info = [notification userInfo];
        CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

        UIEdgeInsets contentInset = self.scrollView.contentInset;
        contentInset.bottom = keyboardRect.size.height;
        self.scrollView.contentInset = contentInset;
    }

    - (void)keyboardWillBeHidden:(NSNotification*)notification
    {
        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollView.contentInset = contentInsets;
    }

    #pragma mark TextField Delegates
    - (BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }

答案 2 :(得分:7)

以下是使用Swift的解决方案:

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
    }

}

答案 3 :(得分:1)

BSKeyboardControl是一个不错的控件。您需要在视图中提供文本字段。一个实现它的一些委托方法。然后这样做太简单了。带有上一个和下一个按钮的工具栏可用于循环显示的文本字段。以下链接将为您提供有关BSKeyboardControl

的详细说明

https://github.com/simonbs/BSKeyboardControls#usage

答案 4 :(得分:1)

改变一个功能:

- (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);
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.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
    [scrollView setContentOffset:CGPointMake(0,aRect.size.height) animated:YES];
}}

答案 5 :(得分:0)

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //添加键盘弹出通知
    [[NSNotificationCenter defaultCenter]addObserver:self  selector:@selector(didChangeKeyBoardFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)viewDidAppear:(BOOL)animated
{
    //设置原始contentSize;
    [super viewDidAppear:animated];
    originalSize = self.mscrollView.contentSize;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //移除键盘弹出通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

pragma mark - private

-(void)didChangeKeyBoardFrame:(NSNotification *)sender
{
    CGRect  endRect  = [[sender.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];

    CGPoint  mf =[self.view convertPoint:CGPointMake(0,self.name_textfieldDown.frameBottom) fromView:self.mscrollView];

    //does the keyboard  cover my label
    CGFloat distance =   mf.y  - endRect.origin.y;

    // it  mean that keyboard will hidden
    if(endRect.origin.y == ScreenHeight)
    {
        // place scrollView back
        [UIView animateWithDuration:0.25 animations:^{
                    self.mscrollView.contentOffset = CGPointMake(0,  self.mscrollView.contentSize.height-  self.mscrollView.height);
            self.mscrollView.contentSize = originalSize;
        }];
    }
    else if (distance>0)
    {
        //
        [UIView animateWithDuration:0.25 animations:^{
            CGSize contentSize = originalSize;
            contentSize.height +=( endRect.size.height  ) ;// I want  users can drag scrollView to buttom when keyboard is showing
            self.mscrollView.contentSize = contentSize;
            self.mscrollView . contentOffset = CGPointMake(0, self.mscrollView.contentOffset.y + distance+20);
        }];
    }
}

答案 6 :(得分:0)

UITextField * activeField; 对于activeField,您必须在.m文件中声明