프로그래밍 방식으로 UITextField 키보드 유형 변경


175

프로그래밍 방식으로 uitextfield의 키보드 유형을 변경하여 다음과 같은 것이 가능합니까?

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

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

3
난 당신이 용어를 변경 좋을 것 doozySO 북미 한 국제 사이트와 아닙니다 .. 더 많이 이해할 수 뭔가 마음에 계속
— abbood

답변:


371

에 대한 keyboardType속성이 있습니다 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;

코드를 읽어야합니다

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

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

7
영리하고 삐걱 거리는 사용자가 다른 문자를 입력하는 것을 막지는 않습니다. 예를 들어 : 숫자 필드를 누르기 전에 이모티콘 키보드가 활성화 되어 있으면 웃는 얼굴을 자유롭게 입력 할 수 있습니다. 이 당신이 이것에 대해 할 수있는 일은 없다, 그것은 확실히 애플의 버그,하지만 당신은 해야 당신이 숫자 필드에 비 숫자를 얻는 경우 확인 코드가 충돌하지 않는합니다.
— Steven Fisher

오늘 발견 된 것은 UITextInputTraits이것이 UITextField채택한 프로토콜 의 속성입니다 .
— rounak

1
웹보기에로드 된 HTML 입력 필드에 대해 키보드 유형을 UIKeyboardTypeNumbersAndPunctuation으로 프로그래밍 방식으로 변경할 수 있습니까?
— Srini

각 키보드 유형으로 하나의 프로젝트에서 프로그래밍 방식으로 uitextfield를 만들었습니다. 이것은 며칠 전에 시작되었습니다. 그러나 지금 이것은 작동하지 않습니다. 실제 이유를 얻지 못함
— Rahul Phate

78

당신이 원한다면 것을주의 그것의 가치가 현재에 초점을 맞춘 바로 키보드 유형을 업데이트 할 필드를 하나 추가 단계가있다 :

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

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

에 대한 호출이 없으면 reloadInputViews선택한 필드 ( 첫 번째 응답기 )가 포커스를 잃고 다시 얻을 때까지 키보드가 변경되지 않습니다 .

전체 UIKeyboardType값 목록은 여기 또는 에서 찾을 수 있습니다 .

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

이 정보는 유용한 정보입니다. 현재 초점이 맞춰진 필드 입력 변경에 대한 정보를 추출하기 위해 Q & A 스타일의 자체 답변 질문을 제안하는 것이 좋습니다 (이 답변을 찾았을 때 찾고 있던 내용)
— Stonz2

1
현재 초점이 맞지 않은 텍스트 필드에서 reloadInputViews를 호출해도 키보드 유형이 즉시 변경되지는 않습니다. 먼저 [에 textField reloadInputViews] [becomeFirstResponder 텍스트 필드] 그래서 더 나은 전화
— Qiulang

1
그것은이었다 [textField reloadInputViews];내가 실종되었다. 감사!
— 이슬람 Q.

1
호출 reloadInputViews은 맞춤형 UITextInput구현 에도 적용됩니다.
— Paul Gardiner

23

예, 예를 들면 다음과 같습니다.

[textField setKeyboardType:UIKeyboardTypeNumberPad];

9
    textFieldView.keyboardType = UIKeyboardType.PhonePad

이것은 신속합니다. 또한이 기능이 제대로 작동하려면 다음에 설정해야합니다.textFieldView.delegate = self


7

텍스트 필드에 영숫자 만 허용하게하려면이 속성을 설정하십시오.

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

스위프트 4

조건이 충족 될 때 키보드 유형을 변경하려는 경우 다음을 수행하십시오. 예를 들어 , 텍스트 필드의 수가 4 또는 5 일 때 키보드 유형을 기본값 에서 숫자 패드 로 변경하려면 다음을 수행하십시오.

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

라는 속성이 keyboardType있습니다. 당신이하고 싶은 것하면 문자열이 어디에 교체입니다 @"Number Pad과 @"Default함께 UIKeyboardTypeNumberPad와 UIKeyboardTypeDefault.

새 코드는 다음과 같아야합니다.

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

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

행운을 빕니다!


1

UIDatePicker입력 으로 사용하려는 사람들을 위해 :

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

이것은 UIKeyboardTypes스위프트 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
}

다음은 목록에서 키보드 유형을 사용하는 예입니다.

textField.keyboardType = .numberPad

0

프로그래밍 방식으로 UITextField 키보드 유형 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

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
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.