ios - 如何在IOS中动态计算文本字段中的字符数

标签 ios objective-c cocoa-touch

我希望能够随时计算 200 - 字符数。 这意味着我想显示字符数,并在用户输入或删除字符时更新它。

我的代码正确地计算了 200 - 任何时候的字符数,但我不知道如何不断更新文本字段。

-(void)updateLabel{
// Get the text from the message
// find the length of the text
// subtract from the converted number in the charCounter Label
// display in the charCounter Label

 int length = _message.text.length;
 int charLeft = 200 - length;
 NSString* charCountStr = [NSString stringWithFormat:@"%i", charLeft];
 _charCounter.text = charCountStr;

}

然后我在 viewDidLoad 中调用 updateLabel 函数。

我怀疑一定有其他函数来持久更新viewController

最佳答案

只需实现 UITextFieldDelegate 方法 textField:shouldChangeCharactersInRange:replacementString: 并从其中调用 updateLabel 方法即可。

From the docs:

The text field calls this method whenever the user types a new character in the text field or deletes an existing character.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    [self updateLabel];

    return YES;
}

不要忘记设置文本字段的委托(delegate)属性,并确保您的类符合 UITextFieldDelegate。

关于ios - 如何在IOS中动态计算文本字段中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24196314/

相关文章:

ios - 为什么这段代码有效?

iphone - 问题滚动 TableView 与内容插入

objective-c - 编写一个 NSPredicate,如果不满足条件则返回 true

ios - xcode UIBarButtonItem View

ios - Swift - 只能打印对象的内存地址

ios - 如何使用 .whereKey 修改查询,但在 Xcode 中使用多个不同的参数?

objective-c - MKOverlayRenderer 在 map View 上显示 UIImage

iOS 应用程序安装网址

ios - RestKit:一对多关系映射

ios - 为什么在打印核心位置返回到控制台的位置时出现无限循环?