如何知道 iOS 中的 UITextField 是否有空格 [英] How to know if a UITextField in iOS has blank spaces

查看:23
本文介绍了如何知道 iOS 中的 UITextField 是否有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITextField,用户可以在其中输入名称并保存.但是,不应允许用户在 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 - 我如何知道用户是否在 textFiled 中输入了两个空格或完整的空格

2 - 我怎么知道 textFiled 是否只填充了空格

编辑 - 仅输入空格(空格)无效

推荐答案

您可以修剪"文本,即删除开头和结尾的所有空格.如果剩下的只是一个空字符串,那么只输入了空格(或什么都不输入).

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.

NSString *rawString = [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
    // Text was empty or only whitespace.
}

如果你想检查是否有任何空格(文本中的任何地方),你可以这样做:

If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:

NSRange range = [rawString rangeOfCharacterFromSet:whitespace];
if (range.location != NSNotFound) {
    // There is whitespace.
}

如果您想完全阻止用户输入空格,请参阅@Hanon 的解决方案.

If you want to prevent the user from entering whitespace at all, see @Hanon's solution.

这篇关于如何知道 iOS 中的 UITextField 是否有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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