如何知道 iOS 中的 UITextField 是否有空格
我有一个 UITextField,用户可以在其中输入名称并保存。但是,不应允许用户在文本字段中输入空格。
1 - 我如何知道用户是否在textFiled中输入了两个空格或完整的空格
2 - 我如何知道textFiled是否仅填充了空格
编辑 - 只输入空格(空格)是无效的
I have a UITextField where user can enter a name and save it. But, user should not be allowed to enter blank spaces in the textFiled.
1 - How can I find out,if user has entered two blank spaces or complete blank spaces in the textFiled
2 - How can i know if the textFiled is filled only with blank spaces
edit - It is invalid to enter only white spaces(blank spaces)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以“修剪”文本,即删除开头和结尾处的所有空白。如果剩下的只是空字符串,则仅输入空格(或不输入任何内容)。
如果您想检查是否有任何空格(文本中的任何位置),您可以这样做:
如果您想完全阻止用户输入空格,请参阅@Hanon's解决方案。
You can "trim" the text, that is remove all the whitespace at the start and end. If all that's left is an empty string, then only whitespace (or nothing) was entered.
If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:
If you want to prevent the user from entering whitespace at all, see @Hanon's solution.
如果您确实想“限制”用户输入空格,
您可以在 UITextFieldDelegate 中实现以下方法
如果用户在字段中输入空格,则当前文本不会发生变化
if you really want to 'restrict' user from entering white space
you can implement the following method in UITextFieldDelegate
If user enter space in the field, there is no change in the current text
以下代码,请使用以下代码行
如果您想限制用户使用
Use following lines of code
if you want to restrict user use below code
UPD: Swift 2.0 支持
UPD: Swift 2.0 Support
我有同样的条件不允许用户输入空白字段
这是我的代码和检查语句
I had a same condition not allowing user to input blank field
Here is my code and check statement
这是 Swift 3 版本
Heres Swift 3 version
在 Swift 中,
如果你想限制用户,可以使用
contains()
例如,
In Swift,
if you want to restrict the user, you can use
contains()
For Example,
这是我使用 stringByReplacingOccurrencesOfString 所做的事情。
Here's what I did using
stringByReplacingOccurrencesOfString
.@Hanon 的答案非常简洁,但我需要的是至少允许 1 个空格,因此根据 Hanon 的解决方案,我做了这个:
我声明了一个名为 whitespaceCount 的局部变量来保留空格的计数。
希望这对任何人都有帮助!
@Hanon's answer is the pretty neat, but what I needed was to allow at least 1 white space, so based on Hanon's solution I made this one:
I declared a local variable called whitespaceCount to keep the counts of the white spaces.
Hope this helps anybody!