如何在Swift中限制UITextField中的某些字符? [英] How to restrict certain characters in UITextField in Swift?

查看:74
本文介绍了如何在Swift中限制UITextField中的某些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Trivia应用程序,该应用程序在启动时要求输入用户名.我想禁止使用#$ @!^&等字符等等(也包括空格").我在此处 a>,但它完全用Objective-C编写.预先感谢.

I am creating a trivia application that asks for a username on start up. I'd like to make it impossible to use characters such as #$@!^& etc (also including "space"). I took a look at this post here but it is written entirely in Objective-C. Thanks in advance.

推荐答案

在基于扩展名的Swift 4 iOS 11.2.x中,测试该示例中的字符串是否为有效的十六进制数字.

Swift 4 iOS 11.2.x based on using an extension, tests to see if a string is a valid hex number in this example.

extension String {

var containsValidCharacter: Bool {
    guard self != "" else { return true }
    let hexSet = CharacterSet(charactersIn: "1234567890ABCDEFabcdef")
    let newSet = CharacterSet(charactersIn: self)
    return hexSet.isSuperset(of: newSet)
  }
}

您可以像使用UITextFieldDelegate一样使用它.

You use it like with the UITextFieldDelegate.

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

尽管我在较早的文章中读到,CharacterSet不支持由多个Unicode组成的字符.所以我要谨慎使用.

Although I read in an earlier post that CharacterSets do not support characters that are composed of more than one Unicode.Scalar; so use with caution I guess.

这篇关于如何在Swift中限制UITextField中的某些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆