ios UItextfield 中的大写字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21092182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:06:30  来源:igfitidea点击:

Uppercase characters in UItextfield

iosiphoneuitextfielduistoryboard

提问by Safari

I have a question about iOS UIKeyboard.

我有一个关于iOS UIKeyboard.

I have a UITextFieldand I would to have the keyboardwith only uppercase characters.

我有一个UITextField,我希望keyboard只有大写字符。

I use a storyboardand I tried to set the Cpitalizationas "All characters" to UITextField properties.

我使用 astoryboard并尝试将其设置Cpitalization为“ All characters”到UITextField properties.

But this not solve my problem...any suggestion?

但这并不能解决我的问题……有什么建议吗?

回答by codercat

Set your textfield type autocapitalizationTypeto UITextAutocapitalizationTypeAllCharacterson the UITextField

将您的文本字段类型设置autocapitalizationTypeUITextAutocapitalizationTypeAllCharacters在 UITextField 上

self.yourTexField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;

After call delegate

通话委托后

// delegate method

// 委托方法

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSRange lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

    if (lowercaseCharRange.location != NSNotFound) {
        textField.text = [textField.text stringByReplacingCharactersInRange:range
                                                                 withString:[string uppercaseString]];
        return NO;
    }

    return YES;
}

回答by Dan

One issue I have with some of the above answers is if you try and set textfield.text, you will lose the cursor position. So if a user tries to edit the middle of the text, the cursor will jump to the end.

我对上述一些答案的一个问题是,如果您尝试设置textfield.text,您将丢失光标位置。因此,如果用户尝试编辑文本的中间,光标将跳到结尾

Here is my Swift solution, still using UITextFieldDelegate:

这是我的 Swift 解决方案,仍在使用UITextFieldDelegate

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if textField == textFieldToUppercase {
        if string == "" {
            // User presses backspace
            textField.deleteBackward()
        } else {
            // User presses a key or pastes
            textField.insertText(string.uppercaseString)
        }
        // Do not let specified text range to be changed
        return false
    }

    return true
}

回答by Tim S

For those looking for a Swift version.

对于那些寻找 Swift 版本的人。

Swift 4

斯威夫特 4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    textField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())

    return false
}

Original answer

原答案

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    textField.text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string.uppercaseString)

    return false
}

Using the Capitalization: All Charactersproperty just forces keyboard to open with caps lock on, but lets the user to turned it off.

使用该Capitalization: All Characters属性只会强制键盘在大写锁定的情况下打开,但允许用户将其关闭。

回答by Eden

The syntax is now

语法现在是

Swift 2

斯威夫特 2

textField.autocapitalizationType = UITextAutocapitalizationType.AllCharacters

Swift 3

斯威夫特 3

textField.autocapitalizationType = .allCharacters

回答by CodeBender

This is a different approach I used, where it does the following:

这是我使用的一种不同的方法,它执行以下操作:

  1. Enforces capitalization as soon as the character is entered
  2. Catches situations where the user disables caps lock even if it textfield is set to auto caps
  3. Allows for easy editing
  4. Works with Swift 2.2
  1. 输入字符后立即强制大写
  2. 捕获用户禁用大写锁定的情况,即使文本字段设置为自动大写
  3. 允许轻松编辑
  4. 适用于 Swift 2.2

First, register a notification to be updated whenever any changes occur in the textfield.

首先,注册一个通知,以便在文本字段中发生任何更改时进行更新。

    textField.addTarget(self, action: #selector(YourClassName.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

Then, implement textFieldDidChange.

然后,实施textFieldDidChange.

func textFieldDidChange(textField: UITextField) {
    textField.text = textField.text?.uppercaseString
}

I chose this to avoid a situation where the user sees an uneven experience of some capitalized, but then changed once they move to the next character.

我选择这个是为了避免用户看到一些大写的不均匀体验,但一旦他们移动到下一个字符就改变了。

回答by Adnan Aftab

Set UITextFieldproperty autocapitalizationTypeto UITextAutocapitalizationTypeAllCharacters. This will make all characters to appear in upper case. Also visit hereto find more about textfields

UITextField属性设置autocapitalizationTypeUITextAutocapitalizationTypeAllCharacters. 这将使所有字符以大写形式出现。另请访问此处以了解有关文本字段的更多信息

回答by Matías Contreras Selman

Swift 4.0 Version:

斯威夫特 4.0 版本:

First set the delegate for the textfield you want to uppercase to the current ViewController (click drag from the textfield to the currentViewController to set the delegate).

首先将要大写的文本字段的委托设置为当前 ViewController(单击从文本字段拖动到 currentViewController 以设置委托)。

After add the extension:

添加扩展后:

extension CurrentViewController: UITextFieldDelegate{

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        //refference to the textfield you want to target
        if textField.tag == 5{
            textField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
            return false
        }
        return true
    }
}

回答by vilas deshmukh

Swift 3 / Swift 4 / Swift 5

斯威夫特 3 / 斯威夫特 4 / 斯威夫特 5

Just one line code in ViewDidLoad/ViewDidAppear:

ViewDidLoad/ViewDidAppear 中只有一行代码:

If you simply want to see the characters typed regardless of the UPPER/lower case to all CAPITALS/UPPER CASE paste below code either in ViewDidLoad/ViewDidAppear

如果您只想查看键入的字符,而不管大写/小写到所有大写/大写,请在 ViewDidLoad/ViewDidAppear 中粘贴下面的代码

self.myTextField.autocapitalizationType = .allCharacters

self.myTextField.autocapitalizationType = .allCharacters

above line changes all letters into CAPITALS while you type automatically

当您自动键入时,以上行将所有字母更改为大写

回答by Enrico F.

You should avoidto use delegate method

你应该避免使用委托方法

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

because this will trigger an unwanted behaviour with iOS 13 + QuickPath typing (the iOS' Swiftkey Keyboard counterpart).

因为这会在 iOS 13 + QuickPath 输入(iOS 的 Swiftkey 键盘对应物)中触发不需要的行为。

If you swipe on the keyboard and write "hello", it will write "HELLOHELLOHELLOHELLOHELLO" into the textfield. This is because the method is called multiple times and it appends the just changed text via textField.text = uppercasedValue.

如果您在键盘上滑动并输入“hello”,它会在文本字段中写入“HELLOHELLOHELLOHELLOHELLO”。这是因为该方法被多次调用,并且它通过textField.text = uppercasedValue.

The right way is to observe the .editingChangeevent and uppercase then the value. For example:

正确的方法是观察.editingChange事件和大写然后是值。例如:

func awakeFromNib() {
    textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
}

and

@objc func textFieldDidChange() {
    textField.text = textField.text?.uppercased()
}

回答by Marek Staňa

Finally I found the way that respects also editing text in the middle of the string in UITextField.

最后,我找到了在UITextField.

The problem is that if you replace whole text by UITextFiled.textproperty the actual cursor moves to end of text. So you need to use .replace()method to specify exactly which characters you want to update to upperCase.

问题是,如果您按UITextFiled.text属性替换整个文本,实际光标将移动到文本末尾。因此,您需要使用.replace()方法来准确指定要更新为大写的字符。

Last thing is to return string.isEmptyas return value of function - otherwise you are not allowing deleting of text.

最后一件事是string.isEmpty作为函数的返回值返回 - 否则你不允许删除文本。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if let text = textField.text, let textRange = Range(range, in: text) {
        let uppercasedString = string.uppercased()
        let updatedText = text.replacingCharacters(in: textRange, with: uppercasedString)
        if let selectedTextRange = textField.selectedTextRange {
            textField.replace(selectedTextRange, withText: uppercasedString)
            approveButtonState(vin: updatedText)
        }
        return string.isEmpty
    }
    return false
}