Как добавить кнопку "Готово" к клавиатуре numpad в iOS
Итак, клавиатура numpad по умолчанию не имеет кнопки "Готово" или "Далее", поэтому я хотел бы добавить ее. В iOS 6 и ниже были некоторые трюки, чтобы добавить кнопку на клавиатуру, но они, похоже, не работают в iOS 7.
Сначала я подписываюсь на клавиатуру с уведомлением
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
Затем я пытаюсь добавить кнопку при появлении клавиатуры:
- (void)keyboardWillShow:(NSNotification *)note
{
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
doneButton.frame = CGRectMake(0, 50, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(dismissKeyboard) 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 view found; add the custom button to it
if([[keyboard description] hasPrefix:@"UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
Но цикл for не запускается, потому что он не находит никаких подзонов. Какие-либо предложения? Я не мог найти никаких решений для iOS7, так есть ли другой способ, которым я должен это делать?
Редактировать: Спасибо за все предложения для парней из панелей инструментов, но я бы предпочел не идти по этому маршруту, поскольку я довольно беден (и это довольно уродливо).
Ответы
Ответ 1
Это простой способ проецирования сделанной кнопки в iOS7 num-keypad. В нижеприведенном делететом UITextField добавьте уведомление для показа клавиатуры.
-(void)textFieldDidBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
Теперь реализуем метод keyboardWillShow
, как показано ниже. Здесь мы должны проявлять особую осторожность к iOS7.
- (void)keyboardWillShow:(NSNotification *)note {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:@"doneButtonNormal.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"doneButtonPressed.png"] forState:UIControlStateHighlighted];
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
dispatch_async(dispatch_get_main_queue(), ^{
UIView *keyboardView = [[[[[UIApplication sharedApplication] windows] lastObject] subviews] firstObject];
[doneButton setFrame:CGRectMake(0, keyboardView.frame.size.height - 53, 106, 53)];
[keyboardView addSubview:doneButton];
[keyboardView bringSubviewToFront:doneButton];
[UIView animateWithDuration:[[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]-.02
delay:.0
options:[[note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]
animations:^{
self.view.frame = CGRectOffset(self.view.frame, 0, 0);
} completion:nil];
});
}else {
// locate keyboard view
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@"UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
});
}
}
Теперь добавьте этот макрос в подходящий заголовок, чтобы обнаружить SYSTEM_VERSION
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
Ответ 2
Более безопасный подход заключается в использовании кнопки UIToolBar
с Done
как inputAccessoryView
.
Пример кода:
UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered target:self
action:@selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
txtField.inputAccessoryView = keyboardDoneButtonView;
Ваш метод -doneClicked
должен выглядеть следующим образом:
- (IBAction)doneClicked:(id)sender
{
NSLog(@"Done Clicked.");
[self.view endEditing:YES];
}
Пример кода Swift:
let keyboardDoneButtonView = UIToolbar.init()
keyboardDoneButtonView.sizeToFit()
let doneButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self,
action: Selector("doneClicked:")))
keyboardDoneButtonView.items = [doneButton]
textFieldInput.inputAccessoryView = keyboardDoneButtonView
Ваш метод -doneClicked
должен выглядеть следующим образом:
func doneClicked(sender: AnyObject) {
self.view.endEditing(true)
}
Ответ 3
Еще проще:
Swift 3.0 и выше:
func addDoneButton() {
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done,
target: view, action: #selector(UIView.endEditing(_:)))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
}
Swift 2.3 и ниже:
func addDoneButton() {
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done,
target: view, action: #selector(UIView.endEditing(_:)))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
}
Цель C:
- (void)addDoneButton {
UIToolbar* keyboardToolbar = [[UIToolbar alloc] init];
[keyboardToolbar sizeToFit];
UIBarButtonItem *flexBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self.view action:@selector(endEditing:)];
keyboardToolbar.items = @[flexBarButton, doneBarButton];
self.textField.inputAccessoryView = keyboardToolbar;
}
EDIT:
Я создал полезную библиотеку под названием DCKit, у которой уже есть панель инструментов:
![Готово панель инструментов над клавиатурой в iOS (с использованием библиотеки DCKit)]()
В нем также есть много других интересных функций.
Ответ 4
Просто основываясь на ответах выше с версией Swift, так как мне пришлось перевести его:
@IBOutlet weak var numberTextField: UITextField!
override func viewDidLoad() {
addDoneButtonTo(numberTextField)
}
// MARK: Done for numberTextField
private func addDoneButtonTo(textField: UITextField) {
let flexBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "didTapDone:")
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
}
func didTapDone(sender: AnyObject?) {
numberTextField.endEditing(true)
}
Ответ 5
Вы можете использовать
myTextField.inputAccessoryView = _inputView;
входной вид аксессуара - это представление, которое всегда появляется на клавиатуре и отклоняется с помощью [textfield resignFirstResponder]
поместите done поверх представления ввода и выполните resignfirstответчик текстовых полей.
Ответ 6
Просто используйте
yourTextField.inputAccessoryView
надеюсь, что вы поможете
Ответ 7
enter code here
1. register the controller to the notification
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Keyboard events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
2. don't forget to remove the controller from the notification centre
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.view endEditing:YES];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
3. implement keyboard notification handlers
- (void)keyboardWillShow:(NSNotification *)notification {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 107, 106, 53);
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(doneButton:)forControlEvents:UIControlEventTouchUpInside];
// save the reference to the button in order to use it in keyboardWillHide method
self.donekeyBoardBtn = doneButton;
// to my mind no need to search for subviews
UIWindow *windowContainigKeyboard = [[[UIApplication sharedApplication] windows] lastObject];
[windowContainigKeyboard addSubview:self.donekeyBoardBtn];
self.donekeyBoardBtn.frame = CGRectMake(0., CGRectGetHeight(w.frame) - CGRectGetHeight(self.donekeyBoardBtn.frame), CGRectGetWidth(self.donekeyBoardBtn.frame), CGRectGetHeight(self.donekeyBoardBtn.frame));
}
- (void)keyboardWillHide:(NSNotification *)notification {
[self.donekeyBoardBtn removeFromSuperview];
}
4. implement done button action
- (void)doneButton:(id)sender{
// add needed implementation
[self.view endEditing:YES];
}
Ответ 8
Здесь приведен пример отображения кнопок с панелью инструментов с клавиатурой.
Ответ 9
Вам нужно определить, находитесь ли вы на телефоне или iPad, так как iPad реализует ключ возврата на панели "число"
Ответ 10
Вид клавиатуры можно найти hasPrefix: @ "UIKeyboard", кнопка не может быть добавлена в качестве подвью. Здесь мое решение: введите ссылку здесь