Programowo zmień typ klawiatury UITextField


175

Czy można programowo zmienić typ klawiatury w uitextfield, aby było możliwe coś takiego:

if(user is prompted for numeric input only)
    [textField setKeyboardType: @"Number Pad"];

if(user is prompted for alphanumeric input)
    [textField setKeyboardType: @"Default"];

3
sugerowałbym zmianę tego terminu doozyna coś, co jest bardziej zrozumiałe. pamiętaj, że SO to strona międzynarodowa, a nie północnoamerykańska
— opactwo

Odpowiedzi:


371

Istnieje keyboardTypenieruchomość na UITextField:

typedef enum {
    UIKeyboardTypeDefault,                // Default type for the current input method.
    UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain active
    UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
    UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
    UIKeyboardTypeNumberPad,              // A number pad (0-9). Suitable for PIN entry.
    UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
    UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
    UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).
    UIKeyboardTypeDecimalPad,             // A number pad including a decimal point
    UIKeyboardTypeTwitter,                // Optimized for entering Twitter messages (shows # and @)
    UIKeyboardTypeWebSearch,              // Optimized for URL and search term entry (shows space and .)

    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated

} UIKeyboardType;

Twój kod powinien przeczytać

if(user is prompted for numeric input only)
    [textField setKeyboardType:UIKeyboardTypeNumberPad];

if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];

7
Zauważ, że nie powstrzymuje to sprytnego / obłąkanego użytkownika przed wprowadzaniem innych znaków. Na przykład: jeśli klawiatura Emoji była aktywna, zanim dotknęli pola numerycznego, mogą swobodnie wpisywać w niej buźki. Nic nie możesz na to poradzić i na pewno jest to błąd Apple, ale powinieneś upewnić się, że twój kod nie ulegnie awarii, jeśli w polu liczbowym pojawią się wartości inne niż liczby.
— Steven Fisher

Okazało się dzisiaj, że jest to właściwość UITextInputTraitsprotokołu, który UITextFieldprzyjmuje.
— rounak

1
Czy można programowo zmienić typ klawiatury na UIKeyboardTypeNumbersAndPunctuation, dla pól wejściowych HTML załadowanych w widoku sieci Web?
— Srini

Utworzyłem uitextfield programowo w jednym projekcie z odpowiednim typem klawiatury. dzieje się to kilka dni temu. ale teraz to nie zadziałało. Brak prawdziwego powodu
— Rahul Phate

78

Warto zauważyć, że jeśli chcesz, aby aktualnie skupione pole natychmiast aktualizowało typ klawiatury, jest jeden dodatkowy krok:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];

Bez wywołania reloadInputViewsklawiatura nie zmieni się, dopóki wybrane pole ( pierwsza osoba odpowiadająca ) nie straci i nie odzyska ostrości.

Pełną listę UIKeyboardTypewartości można znaleźć tutaj lub:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

Jest to przydatna informacja - sugerowałbym zrobienie pytania w stylu pytań i odpowiedzi, na które trzeba odpowiedzieć, tylko po to, aby wyodrębnić informacje o aktualnie skoncentrowanej zmianie pola wejściowego (właśnie tego szukałem, gdy znalazłem tę odpowiedź)
— Stonz2

1
Warto również wspomnieć, że wywołanie funkcji reloadInputViews w polu tekstowym, które obecnie NIE jest fokusem, nie zmieni od razu typu klawiatury. Więc lepiej najpierw zadzwoń do [textfield getFirstResponder], a potem [textField reloadInputViews]
— Qiulang,

1
Chodziło o to, [textField reloadInputViews];że mi brakowało. Dzięki!
— Islam Q.

1
Wywołanie reloadInputViewsdziała również w przypadku niestandardowych UITextInputwdrożeń.
— Paul Gardiner,

23

Tak, możesz na przykład:

[textField setKeyboardType:UIKeyboardTypeNumberPad];

9
    textFieldView.keyboardType = UIKeyboardType.PhonePad

To jest szybkie. Aby to działało poprawnie, musi być ustawione potextFieldView.delegate = self


7

aby pole tekstowe akceptowało tylko znaki alfanumeryczne, ustaw tę właściwość

textField.keyboardType = UIKeyboardTypeNamePhonePad;

6
_textField .keyboardType = UIKeyboardTypeAlphabet;
_textField .keyboardType = UIKeyboardTypeASCIICapable;
_textField .keyboardType = UIKeyboardTypeDecimalPad;
_textField .keyboardType = UIKeyboardTypeDefault;
_textField .keyboardType = UIKeyboardTypeEmailAddress;
_textField .keyboardType = UIKeyboardTypeNamePhonePad;
_textField .keyboardType = UIKeyboardTypeNumberPad;
_textField .keyboardType = UIKeyboardTypeNumbersAndPunctuation;
_textField .keyboardType = UIKeyboardTypePhonePad;
_textField .keyboardType = UIKeyboardTypeTwitter;
_textField .keyboardType = UIKeyboardTypeURL;
_textField .keyboardType = UIKeyboardTypeWebSearch;

5

Szybki 4

Jeśli próbujesz zmienić typ klawiatury, gdy warunek jest spełniony, postępuj zgodnie z tym. Na przykład: Jeśli chcemy zmienić typ klawiatury z domyślnej na klawiaturę numeryczną, gdy liczba pól tekstowych wynosi 4 lub 5, zrób tak:

textField.addTarget(self, action: #selector(handleTextChange), for: .editingChanged)

@objc func handleTextChange(_ textChange: UITextField) {
 if textField.text?.count == 4 || textField.text?.count == 5 {
   textField.keyboardType = .numberPad
   textField.reloadInputViews() // need to reload the input view for this to work
 } else {
   textField.keyboardType = .default
   textField.reloadInputViews()
 }

2

Jest do tego właściwość o nazwie keyboardType. Co będziemy chcieli zrobić, to wymienić, gdzie trzeba sznurki @"Number Padi @"Defaultz UIKeyboardTypeNumberPadi UIKeyboardTypeDefault.

Twój nowy kod powinien wyglądać mniej więcej tak:

if(user is prompted for numeric input only)
    [textField setKeyboardType:UIKeyboardTypeNumberPad];

else if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];

Powodzenia!


1

dla osób, które chcą użyć UIDatePickerjako danych wejściowych:

UIDatePicker *timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 0, 0)];
[timePicker addTarget:self action:@selector(pickerChanged:)
     forControlEvents:UIControlEventValueChanged];
[_textField setInputView:timePicker];

// pickerChanged:
- (void)pickerChanged:(id)sender {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d/M/Y"];
    _textField.text = [formatter stringFromDate:[sender date]];
}

1

To jest UIKeyboardTypesdla Swift 3:

public enum UIKeyboardType : Int {

    case `default` // Default type for the current input method.
    case asciiCapable // Displays a keyboard which can enter ASCII characters
    case numbersAndPunctuation // Numbers and assorted punctuation.
    case URL // A type optimized for URL entry (shows . / .com prominently).
    case numberPad // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.
    case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
    case namePhonePad // A type optimized for entering a person's name or phone number.
    case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

    @available(iOS 4.1, *)
    case decimalPad // A number pad with a decimal point.

    @available(iOS 5.0, *)
    case twitter // A type optimized for twitter text entry (easy access to @ #)

    @available(iOS 7.0, *)
    case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).

    @available(iOS 10.0, *)
    case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.


    public static var alphabet: UIKeyboardType { get } // Deprecated
}

Oto przykład użycia typu klawiatury z listy:

textField.keyboardType = .numberPad

0

Programowo zmień typ klawiatury UITextField na Swift 3.0

lazy var textFieldTF: UITextField = {

    let textField = UITextField()
    textField.placeholder = "Name"
    textField.frame = CGRect(x:38, y: 100, width: 244, height: 30)
    textField.textAlignment = .center
    textField.borderStyle = UITextBorderStyle.roundedRect
    textField.keyboardType = UIKeyboardType.default //keyboard type
    textField.delegate = self
    return textField 
}() 
override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(textFieldTF)
}

0

Oto typ klawiatury w Swift 4.2

// UIKeyboardType
//
// Requests that a particular keyboard type be displayed when a text widget
// becomes first responder. 
// Note: Some keyboard/input methods types may not support every variant. 
// In such cases, the input method will make a best effort to find a close 
// match to the requested type (e.g. displaying UIKeyboardTypeNumbersAndPunctuation 
// type if UIKeyboardTypeNumberPad is not supported).
//
public enum UIKeyboardType : Int {


    case `default` // Default type for the current input method.

    case asciiCapable // Displays a keyboard which can enter ASCII characters

    case numbersAndPunctuation // Numbers and assorted punctuation.

    case URL // A type optimized for URL entry (shows . / .com prominently).

    case numberPad // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.

    case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).

    case namePhonePad // A type optimized for entering a person's name or phone number.

    case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

    @available(iOS 4.1, *)
    case decimalPad // A number pad with a decimal point.

    @available(iOS 5.0, *)
    case twitter // A type optimized for twitter text entry (easy access to @ #)

    @available(iOS 7.0, *)
    case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).

    @available(iOS 10.0, *)
    case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.


    public static var alphabet: UIKeyboardType { get } // Deprecated
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.