简体   繁体   English

获取NSTextField的text属性的长度

[英]Getting the length of an NSTextField's text property

I am having a problem finding the length of a text field's text ! 我在查找文本字段的text长度时遇到问题!

I searched here a lot and just found that it would work with textfield.text.length or something like that. 我在这里搜索了很多内容,发现它可以与textfield.text.length或类似的东西一起使用。
My problem is textfield.text is not working for me! 我的问题是textfield.text对我不起作用! If I write this code: textfield.text; 如果我编写这段代码: textfield.text; then I get an error like this: 然后我得到这样的错误:

property "text" not found on object of type NSTextField NSTextField类型的对象上找不到属性“文本”

I have to find the length of an text field in order to limit the number of characters. 我必须找到文本字段的长度以限制字符数。

What should I do? 我该怎么办? Thanks in advance. 提前致谢。

Most of the classes in AppKit, as opposed to UIKit, don't have properties. 与UIKit相比,AppKit中的大多数类都没有属性。 NSTextField doesn't even have a method called text . NSTextField甚至没有名为text的方法。 You need the stringValue method, which is inherited from NSControl 您需要从NSControl继承的stringValue方法

The generally accepted way of doing this (limiting the length of NSTextField) is by using the NSFormatter helper class. 普遍接受的方法(限制NSTextField的长度)是使用NSFormatter帮助器类。 See Here 看这里

To limit the length you add the delegate methods to your controller by adding 为了限制长度,您可以通过以下方式将委托方法添加到控制器中:

< UITextFieldDelegate > 

in the header file. 在头文件中。 Then in the implementation add the following method: 然后在实现中添加以下方法:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

In here just check the length and either return the string or just the string length you want. 在这里,只需检查长度,然后返回字符串或仅返回所需的字符串长度即可。
You can get the length with: 您可以通过以下方式获得长度:

[[textfield stringValue] length]

In interface builder be sure and add the file owner as the delegate to the text field 确保在界面生成器中并将文件所有者作为代理添加到文本字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM