设置 UITextField 最大长度
有没有办法设置 UITextField 的最大长度?
类似于 HTML 输入字段中的 MAXLENGTH 属性。
Is there any way to set the maximum length on a UITextField?
Something like the MAXLENGTH attribute in HTML input fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
这可以正确地与退格键和复制&一起使用。粘贴:
更新:更新为接受返回键,即使在最大长度时也是如此。谢谢罗杰斯先生!
This works correctly with backspace and copy & paste:
UPDATE: Updated to accept the return key even when at MAXLENGTH. Thanks Mr Rogers!
更新
我无法删除此答案,因为它已被接受,但它不正确。这是正确的代码,从下面的 TomA 复制:
ORIGINAL
我认为你的意思是 UITextField。如果是,那么有一个简单的方法。
每次角色点击或之前的角色替换时都会调用该方法。在这个方法中,你可以这样做:
UPDATE
I cannot delete this answer because it is the accepted one, but it was not correct. Here is the correct code, copied from TomA below:
ORIGINAL
I think you mean UITextField. If yes, then there is a simple way.
textField:shouldChangeCharactersInRange:replacementString:
method.That method gets called on every character tap or previous character replacement. in this method, you can do something like this:
正确处理退格并将字符限制为提供的长度限制的更好函数如下:
干杯!
A better function which handles backspaces correctly and limits the characters to the supplied length limit is the following:
Cheers!
此代码限制文本,同时还允许您输入字符或粘贴到文本中的任意位置。如果生成的文本太长,它会更改范围中的字符并将生成的文本截断到限制。
This code limits the text while also allowing you enter characters or paste anywhere into the text. If the resulting text would be too long it changes the characters in the range and truncates the resulting text to the limit.
我认为这段代码可以解决这个问题:
使用这个委托方法,您可以防止用户向文本字段添加超过 MAX_LENGTH 的字符,并且应该允许用户在需要时输入退格键。
I think this code would do the trick:
With this delegate method you can prevent the user to add more characters than MAX_LENGTH to your text field and the user should be allowed to enter backspaces if needed.
对我来说这有魔力:
For me this did the magic:
这就是我解决这个问题的方法。当达到最大限制时,它不会尝试添加更多...您只能删除字符
this is how i resolved that problem. When max limit is reached it wont try to add more... you will only be able to remove chars
我认为没有这样的财产。
但是分配给 UILabel 的文本必须是 NSString。在将此字符串分配给 UILabel 的文本属性之前,您可以使用 NSString 的以下方法在给定索引(您的最大长度)处裁剪字符串:
I think there's no such property.
But the text you assign to the UILabel has to be an NSString. And before you assign this string to the UILabel's text property you can for example use the following method of NSString to crop the string at a given index (your maxlength):
这与 coneybeare 的答案类似,但现在文本字段最多可以包含 MAXLENGTH 符号:
This is similar to coneybeare's answer, but now the text field can contain a maximum of MAXLENGTH symbols:
您必须了解文本放置的位置以及添加的文本的长度(以防粘贴多个字符)。它们之间关于最大长度的模式是它们的总和永远不应超过最大长度。
You have to be aware of the location the text is placed in as well as the length of text being added (in case they're pasting more than one character). The pattern between these with respect to max length is that their sum should never exceed the max length.
您需要在
ViewDidLoad
上分配委托You need to assign delegate on
ViewDidLoad