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

查看:76
本文介绍了如何知道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是否仅填充空格

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

edit - It is invalid to enter only white spaces(blank spaces)

推荐答案

你可以修剪文本,即删除开头和结尾的所有空格。如果剩下的只是一个空字符串,那么只输入空格(或没有)。

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's解决方案。

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

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

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