完成按键仅用于数字键盘

时间:2011-11-23 08:44:49

标签: iphone objective-c ios

我正在开发iPhone应用程序。我在其中一个视图中有四个文本字段。在这四个文本字段中,我有一个文本字段,其中将使用数字键盘。但在数字键盘上没有返回键。所以我通过使用以下代码以编程方式添加了“完成”按钮。

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
    [[NSNotificationCenter defaultCenter] addObserver:self                  
            selector:@selector(keyboardDidShow:) 
                                                 name:UIKeyboardDidShowNotification object:nil];        
} else {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification object:nil];
}

   - (void)addButtonToKeyboard {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
    [doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
} else {        
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
}
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
    keyboard = [tempWindow.subviews objectAtIndex:i];
    // keyboard found, add the button
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                               [keyboard addSubview:doneButton];                
    } else {
        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                   [keyboard addSubview:doneButton];
        }
     }
    }

     - (void)keyboardWillShow:(NSNotification *)note {
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) {

        [self addButtonToKeyboard];


}
  }

       - (void)keyboardDidShow:(NSNotification *)note {
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {

        [self addButtonToKeyboard];


      }
   }


- (void)doneButton:(id)sender {
    NSLog(@"doneButton");
    NSLog(@"Input: %@", contactno.text);

    [contactno resignFirstResponder];

     }

这个特定的文本域很好。但是这个按钮也可以添加到其他文本字段中。如何取消隐藏其他文本字段的按钮。                                 enter image description here

提前多多谢谢。

3 个答案:

答案 0 :(得分:23)

请请,请,请,请,请,请请,请请不要这样做。这是非常脆弱的。考虑一下:

  • 如果数字键盘的布局发生变化怎么办?
  • 如果键的颜色发生变化怎么办?
  • 如果键盘的实现发生变化,使其不再是索引1处的窗口,该怎么办?
  • 如果键盘和外围设备主机的实现发生变化,以便内省描述中断,该怎么办?
  • 如果您在iPad上运行此键盘,键盘的布局完全不同,该怎么办?

这些只是将您的用户界面改为私有视图层次结构所带来的无数问题。

不要这样做。

以下是两种选择:

  1. 在每个-inputAccessoryView上使用UIResponder属性(因此每个UIView)使用“完成”按钮定义UIToolbar。当键盘进出动画时,inputAccessoryView将位于键盘上方。

  2. 在整个用户界面上添加一个透明的UIView,用于捕捉点按事件并导致键盘解除

答案 1 :(得分:1)

我想你可以保留一个全局变量UITextField * selectedTextField作为用户当前选择的textField的指针(弱引用)。同时将IBOutlets存储到视图中的所有UITextField对象(强引用)。然后将整个addButtonToKeyboard主体包装在一个大的if子句中:

if (self.selectedTextField == self.contactNumberTextField){
    // ... add button
}

您需要设置UITextField委托方法

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

知道哪个textField是当前选择的。

事实上我认为你甚至可以在没有出口的情况下使用selectedTextField.keyboardType属性来做,但是再一次,你可能已经有了出口,因为你需要他们从他们那里读取用户输入。

希望这有帮助!

答案 2 :(得分:1)

将此代码放在您的项目中,只需设置文本字段的iboutlet。它也有一些未使用的方法,但您可以使用它选择完成按钮。然后您将删除未使用的方法。这只是为了获取完成按钮数字键盘键盘

.H文件

@interface aaaViewController : UIViewController
{
IBOutlet UITextField *txthello;
UIImage *numberPadDoneImageNormal;
UIImage *numberPadDoneImageHighlighted;
UIButton *numberPadDoneButton;

}

@property (nonatomic, retain) UIImage *numberPadDoneImageNormal;
@property (nonatomic, retain) UIImage *numberPadDoneImageHighlighted;
@property (nonatomic, retain) UIButton *numberPadDoneButton;

.M文件

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

// Add listener for keyboard display events
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardDidShow:) 
                                                 name:UIKeyboardDidShowNotification 
                                               object:nil];     
} else {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:nil];
}

// Add listener for all text fields starting to be edited
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(textFieldDidBeginEditing:)
                                             name:UITextFieldTextDidBeginEditingNotification 
                                           object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardDidShowNotification 
                                                  object:nil];      
} else {
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil];
}
[[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:UITextFieldTextDidBeginEditingNotification 
                                              object:nil];
[super viewWillDisappear:animated];
}

- (UIView *)findFirstResponderUnder:(UIView *)root {
if (root.isFirstResponder)
    return root;    
for (UIView *subView in root.subviews) {
    UIView *firstResponder = [self findFirstResponderUnder:subView];        
    if (firstResponder != nil)
        return firstResponder;
}
return nil;
}

- (UITextField *)findFirstResponderTextField {
UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]];
if (![firstResponder isKindOfClass:[UITextField class]])
    return nil;
return (UITextField *)firstResponder;
}

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

// Remove any previous button
[self.numberPadDoneButton removeFromSuperview];
self.numberPadDoneButton = nil;

// Does the text field use a number pad?
if (textField.keyboardType != UIKeyboardTypeNumberPad)
    return;

// If there's no keyboard yet, don't do anything
if ([[[UIApplication sharedApplication] windows] count] < 2)
    return;
UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];

// Create new custom button
self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53);
self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE;
[self.numberPadDoneButton setTitle:@"Return" forState:UIControlStateNormal];
//  [self.numberPadDoneButton setFont:[UIFont boldSystemFontOfSize:18]];
[self.numberPadDoneButton setTitleColor:[UIColor colorWithRed:77.0f/255.0f green:84.0f/255.0f blue:98.0f/255.0f alpha:1.0] forState:UIControlStateNormal];  

[self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal];
[self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];

// Locate keyboard view and add button
NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard";
for (UIView *subView in keyboardWindow.subviews) {
    if ([[subView description] hasPrefix:keyboardPrefix]) {
        [subView addSubview:self.numberPadDoneButton];
        [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
        break;
    }
}
}

- (void)textFieldDidBeginEditing:(NSNotification *)note {
[self updateKeyboardButtonFor:[note object]];
}

- (void)keyboardWillShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}

- (void)keyboardDidShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}

- (IBAction)numberPadDoneButton:(id)sender {
UITextField *textField = [self findFirstResponderTextField];
[textField resignFirstResponder];
}


- (void)dealloc {
[numberPadDoneImageNormal release];
[numberPadDoneImageHighlighted release];
[numberPadDoneButton release];
[super dealloc];
}