Добавить кнопку, чтобы скрыть клавиатуру - PullRequest
14 голосов
/ 30 мая 2011

В UITextView, чтобы скрыть клавиатуру, есть метод:

...
    textfield.returnKeyType = UIReturnKeyDone;
    textfield.delegate = self;
....

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;

}

, но если я хочу оставить кнопку «сделано» на «возврат» и добавить кнопку, чтобы скрыть клавиатуру,как мне?

Ответы [ 3 ]

38 голосов
/ 30 мая 2011

Вы можете назначить панель инструментов с кнопкой, которая отклоняет клавиатуру, как текстовое поле inputAccessoryView.Быстрый пример будет,

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:textField action:@selector(resignFirstResponder)] autorelease];
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease];
toolbar.items = [NSArray arrayWithObject:barButton];

textField.inputAccessoryView = toolbar;
5 голосов
/ 31 августа 2016

Версия Swift 2.0:

//Declared at top of view controller
var accessoryDoneButton: UIBarButtonItem!
let accessoryToolBar = UIToolbar(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.width, 44))
//Could also be an IBOutlet, I just happened to have it like this
let codeInput = UITextField()

//Configured in viewDidLoad()
self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(self.donePressed(_:)))
self.accessoryToolBar.items = [self.accessoryDoneButton]
self.codeInput.inputAccessoryView = self.accessoryToolBar

Swift 4:

//Declared at top of view controller
var accessoryDoneButton: UIBarButtonItem!
let accessoryToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
//Could also be an IBOutlet, I just happened to have it like this
let codeInput = UITextField()

//Configured in viewDidLoad()
self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.donePressed))
self.accessoryToolBar.items = [self.accessoryDoneButton]
self.codeInput.inputAccessoryView = self.accessoryToolBar

func donePressed() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

Документация UIToolBar

документация "inputAccessoryView"

3 голосов
/ 30 декабря 2011

Это можно сделать намного проще!

Я сделал пользовательское представление в IB в своем viewController.h Я только что создал IBOutlet UIView *accessoryView;, соединил их и - (IBAction)dismissKeyboard;

Я поместил в вид панель инструментов с кнопкой «Готово», установил соединение с IBAction и написал: [textView resignFirstResponder] и

- (void)viewDidLoad
{
    textView.inputAccessoryView = accessoryView;
    [super viewDidLoad];
}

Но на самом деле это выглядит немного странно и не в стиле яблока…идея?

...