简体   繁体   English

如何解雇iOS Decimal键盘?

[英]How to dismiss iOS Decimal keyboard?

I am making an iOS application which required user to enter numeric values for multiple text fields. 我正在制作一个iOS应用程序,要求用户为多个文本字段输入数值。 Under UITextField attributes, I have used 在UITextField属性下,我使用过

Keyboard = Decimal Pad 键盘 =十进制键盘

Return Key = Done 返回键 =完成

The keyboard is taking up the space and hiding the "Submit Form" Button. 键盘占用空间并隐藏“提交表单”按钮。

Under the UIViewController.h file, I have written the following code for each UITextField, with event as Did end on Exit : UIViewController.h文件下,我为每个UITextField编写了以下代码,其中事件为已结束退出

-(IBAction)dismissKeyboard:(id)sender;

Under the UIViewController.m file, I have written the following code for each UITextField: UIViewController.m文件下,我为每个UITextField编写了以下代码:

-(IBAction)dismissKeyboard:(id)sender {

    [textField becomeFirstResponder];
    [textField resignFirstResponder];
}

When I open iOS simulator for Xcode 5, I do not get any DONE field on the on-screen keyboard. 当我为Xcode 5打开iOS模拟器时,我在屏幕键盘上没有任何DONE字段。 However, if I press RETURN key from my MacBook keyboard, the on-screen keyboard goes away. 但是,如果我从MacBook键盘按RETURN键,屏幕键盘就会消失。

How can I - 我怎么能够 -

  • Display the DONE key on the iOS keyboard? 在iOS键盘上显示DONE键?
  • Dismiss the keyboard? 关掉键盘?

Since scroll view has been suggested, I will recommend another approach. 由于建议滚动视图,我将推荐另一种方法。

For each numeric input field, set an input accessory view - a toolbar - with a "Done" button in it. 对于每个数字输入字段,设置输入附件视图 - 工具栏 - 其中包含“完成”按钮。 It will look like the bar above the keyboard in Safari. 它看起来像Safari中键盘上方的条形图。 Once the user taps this Done button, close the keyboard like you normally do. 用户点击此完成按钮后,像平常一样关闭键盘。

This is the simplest solution. 这是最简单的解决方案。

UIToolbar* toolbar = [UIToolbar new];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyboard:)];
id space = [UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
toolbar.items = @[space, doneButton];

self.numericTextField1.inputAccessoryView = toolbar;
self.numericTextField2.inputAccessoryView = toolbar;
...

In .h class, first declare a scroll view. 在.h类中,首先声明一个滚动视图。

@property (strong, nonatomic) IBOutlet UIScrollView *scrRegistration;

In .m class,use these code 在.m类中,使用这些代码

-(void)viewWillAppear:(BOOL)animated 
{
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
    [gesture setNumberOfTapsRequired:1];
    [gesture setNumberOfTouchesRequired:1];
    [self.scrRegistration addGestureRecognizer:gesture];
    [self.scrRegistration setContentSize:CGSizeMake(320, 354)];
    for (UIView *vw in [self.scrRegistration subviews]) {
        if([vw isKindOfClass:[UITextField class]]){
            UITextField *txtfld=(UITextField *)vw;
            txtfld.attributedPlaceholder = [[NSAttributedString alloc] initWithString:txtfld.placeholder attributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:8.0f/255.0f green:94.0f/255.0f blue:165.0f/255.0f alpha:1.0]}];
        }
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if(textField==DecimalKeyboard) {
        if([[UIScreen mainScreen] bounds].size.height>480) {
            [self.scrRegistration setContentOffset:CGPointMake(0, 110) animated:YES];
        } else {
            [self.scrRegistration setContentOffset:CGPointMake(0, 300) animated:YES];
        }
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleBlackTranslucent;
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],
                               nil];
        [numberToolbar sizeToFit];
        textField.inputAccessoryView = numberToolbar;
   }
}




-(void)hideKeyboard:(UITapGestureRecognizer *)tap 
{
    [DecimalKeyboard resignFirstResponder];
    [self.scrRegistration setContentOffset:CGPointMake(0, 0) animated:YES];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView commitAnimations];
}



-(void)cancelNumberPad
{
    for (UIView *vw in [self.scrRegistration subviews]) {
        if([vw isKindOfClass:[UITextField class]]) {
            UITextField *txtfld=(UITextField *)vw;
            if ([txtfld isFirstResponder] == YES) {
                [txtfld resignFirstResponder];
            }
        }
    }

    [self.scrRegistration setContentOffset:CGPointMake(0, 0) animated:YES];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView commitAnimations];
}



-(void)doneWithNumberPad
{
    [DecimalKeyboard resignFirstResponder];
    [self.scrRegistration setContentOffset:CGPointMake(0, 0) animated:YES];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView commitAnimations];
}

You might be better off simply putting the contents on screen into a scrollview, then resizing the view when the keyboard is present. 您可能最好只是将屏幕上的内容放入滚动视图,然后在键盘存在时调整视图大小。 That's typically the approach I take when I have an input form and it's very easy to implement. 这通常是我在输入表单时采用的方法,并且很容易实现。 To do this, you can follow the instructions in this answer: 为此,您可以按照以下答案中的说明操作:

https://stackoverflow.com/a/16044603/3708242 https://stackoverflow.com/a/16044603/3708242

First, make sure you register your viewController for the keyboard notifications (and remove the observers when the view is going away): 首先,确保为键盘通知注册viewController(并在视图消失时删除观察者):

- (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];
}

Here's the main part of the code. 这是代码的主要部分。 It assumes you have a view that takes up the whole screen. 它假设您有一个占据整个屏幕的视图。 If that's not the case, you'll need to tweak the CGRects in the two methods below.: 如果不是这样,你需要在下面两种方法中调整CGRects:

- (void)keyboardWillShow:(NSNotification *)note {
    NSDictionary *userInfo = note.userInfo;
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect keyboardFrameEnd = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardFrameEnd = [self.view convertRect:keyboardFrameEnd fromView:nil];

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
        self.contentView.frame = CGRectMake(0, 0, keyboardFrameEnd.size.width, keyboardFrameEnd.origin.y);
    } completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)note {
    NSDictionary *userInfo = note.userInfo;
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect keyboardFrameEnd = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardFrameEnd = [self.view convertRect:keyboardFrameEnd fromView:nil];

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
        self.contentView.frame = CGRectMake(0, 0, keyboardFrameEnd.size.width, keyboardFrameEnd.origin.y);
    } completion:nil];
}

In case anyone else comes across this question when learning Swift, after a lot of failed attempts I finally had some success with this code in my ViewController, based on Leo Natan's answer above: 如果其他人在学习Swift时遇到这个问题,经过很多失败的尝试后,我终于在我的ViewController中使用此代码取得了一些成功,基于Leo Natan的上述答案:

@IBOutlet var decimalField : UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // ...

    addDoneButtonToKeyboard()

    // ...

    // Do any additional setup after loading the view, typically from a nib.
    refreshUI()
}

func addDoneButtonToKeyboard() {
    var doneButton:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "hideKeyboard")

    var space:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)

    var items = [AnyObject]()
    items.append(space)
    items.append(doneButton)

    toolbar.items = items

    decimalField.inputAccessoryView = toolbar
}

func hideKeyboard() {
    decimalField.resignFirstResponder()
}

You should consider having the input form in a scroll view. 您应该考虑在滚动视图中输入表单。 This way the app can scroll the form so that the submit button becomes visible. 这样,应用程序可以滚动表单,以便提交按钮变得可见。 Your users can also scroll up and down to see all the input. 您的用户还可以向上和向下滚动以查看所有输入。

To have a numerical keyboard with a done button you need to create a custom input view. 要使用带有完成按钮的数字键盘,您需要创建自定义输入视图。

An alternative is to dismiss the keyboard on any tap outside the keyboard and the text fields, but the user experience would be awkward. 另一种方法是在键盘外的任何水龙头和文本字段上关闭键盘,但用户体验会很尴尬。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM