Можно ли программно запустить кнопку «Переключить на цифровую клавиатуру» на клавиатуре iPhone? - PullRequest
10 голосов
/ 28 февраля 2010

Я хочу найти способ программно запустить селектор, который заставляет клавиатуру iPhone переключаться с букв на цифры. Я знаю, что могу переключать тип клавиатуры, но я хочу знать, есть ли способ сделать это без переключения типа клавиатуры.

Ответы [ 4 ]

6 голосов
/ 20 октября 2010

Просто обходной путь: Когда вы хотите изменить плоскость клавиатуры активной клавиатуры, например, с алфавита на цифровую клавиатуру при редактировании UITextField, сначала установите новое значение в свойстве keyboardType текстового поля, затем отправьте resignFirstResponder, наконец, сообщение сталFirstResponder в текстовое поле. Э.Г.

textfield.keyboardType = UIKeyboardTypeNumberPad;
[textField resignFirstResponder];
[textField becomeFirstResponder];

Swift:

textField.keyboardType = .numberPad
textField.resignFirstResponder()
textField.becomeFirstResponder()

Надеюсь, это поможет; -D

6 голосов
/ 01 марта 2010

Вы не можете переключать плоскости клавиш (буквенная клавиатура от цифровой клавиатуры до символьной клавиатуры) программно, по крайней мере, ни в коем случае, если это не поддерживается публично Как вы упомянули, вы можете изменить тип клавиатуры или внешний вид черт ввода текста первого респондента, но это отличается от переключения между различными клавишными плоскостями, что должен делать только пользователь.

1 голос
/ 17 мая 2018

Для пользовательского переключения типов клавиатуры вы можете использовать вспомогательный вид клавиатуры

enter image description here

enter image description here

Код для придания клавиатуре аксессуараПросмотр для переключения типов ... (надеюсь, понятный код понятен)

// You can call this in viewDidLoad (initialization of the ABC/Done view) 
- (void)setAccessoryViewForKeyboard{
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 44)];
    UIBarButtonItem *changeKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(switchKeyboardTypes)];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *choose = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", @"") style:UIBarButtonItemStylePlain target:_textField action:@selector(resignFirstResponder)];
    [toolbar setItems:@[changeKeyboard, space, choose]];
    [self.textField setInputAccessoryView:toolbar];

}

// changing the left button text ('ABC' and '123')
- (void)setTitleForSwitchingKeyboardButton{
    NSString *firstButtonText = self.textField.keyboardType == UIKeyboardTypeDefault ? NSLocalizedString(@"123", @"") : NSLocalizedString(@"ABC", @"");
    [[[(UIToolbar *)self.textField.inputAccessoryView items] firstObject] setTitle:firstButtonText];
}


- (void)switchKeyboardTypes{
    if (self.textField.keyboardType == UIKeyboardTypeDefault){
        [self setTextFieldKeyboardType:UIKeyboardTypeNumberPad];
    } else {
        [self setTextFieldKeyboardType:UIKeyboardTypeDefault];
    }
}

- (void)setTextFieldKeyboardType:UIKeyboardTypeNumberPad:(UIKeyboardType)keyboardType {

    [self.textField setKeyboardType:keyboardType];

    if ([_textField isFirstResponder]) {

        _changingKeyboardType = YES;
        [self.textField resignFirstResponder];
        [self.textField becomeFirstResponder];
        _changingKeyboardType = NO;
    }

    [self setTitleForSwitchingKeyboardButton];
}


-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (!_changingKeyboardType) {
        // you can set the default keyboard type here:
        // [self setTextFieldKeyboardType:UIKeyboardTypeNumberPad];
        // [self setTextFieldKeyboardType:UIKeyboardTypeDefault];
        [self setTitleForSwitchingKeyboardButton];
    }
 }
1 голос
/ 07 июня 2010

Посмотрите на это:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil)
    {
        cell = [ [ [UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        cell.textLabel.textColor = [UIColor whiteColor];
    }

    UITextField * textField = [ [ UITextField alloc] initWithFrame:CGRectMake(55.0f, 10.0f, 230.0f, 31.0f)];
    textField.textColor = [UIColor whiteColor];

    textField.delegate = self;
c this care fully   ///////////if(indexPath.row == 0)
c this care fully   //  textField.keyboardType = UIKeyboardTypeDefault;
c this care fully   //else
c this care fully   //  textField.keyboardType = UIKeyboardTypePhonePad;
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    [cell.contentView addSubview:textField];

    if(indexPath.row == 0)
    {
        self.sender = textField;
        cell.textLabel.text = @"From:";
    }
    else 
    {
        self.mobileNumber = textField; 
        cell.textLabel.text = @"To:";
    }
    [textField release];
    if(indexPath.row == 1)
    {
        UIButton * contactsButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [contactsButton addTarget:self action:@selector(addContact:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = contactsButton;

    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

}

Проверьте, где я прокомментировал "c эта забота полностью"

Это поможет вам программно переключать клавиатуры.

...