【问题标题】:What is a simple way to get the entire text that is inside a UITextField as it is being typed?什么是在输入 UITextField 时获取整个文本的简单方法?
【发布时间】:2013-08-30 00:34:31
【问题描述】:

当用户在 UITextField 中输入内容时,我需要实时了解文本字段中的整个字符串。我这样做的方法是监听UITextFieldDelegate 回调。这个回调的问题是它在实际插入附加文本之前被触发。由于这个和其他各种极端情况,我需要编写这个极其复杂的代码。有没有更简单(更少代码)的方式来做同样的事情?

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString* entireString = nil;

    if (string.length == 0) {
        // When hitting backspace, 'string' will be the empty string.
        entireString = [textField.text substringWithRange:NSMakeRange(0, textField.text.length - 1)];
    } else if (string.length > 1) {
        // Autocompleting a single word and then hitting enter. For example,
        // type in "test" and it will suggest "Test". Hit enter and 'string'
        // will be "Test".
        entireString = string;
    } else {
        // Regular typing of an additional character
        entireString = [textField.text stringByAppendingString:string];
    }

    NSLog(@"Entire String = '%@'", entireString);

    return YES;
}

【问题讨论】:

标签: ios objective-c cocoa-touch uitextfield


【解决方案1】:

我什至不会与代表打交道。只需使用UITextFieldTextDidChangeNotification 在事后通知更改。然后您不必担心将更改附加到字符串,您只需访问整个文本即可。

[[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
    NSString *string = someTextFieldReference.text;
}];

或者正如@warpedspeed 链接的帖子中的答案所指出的那样,您可以为文本字段的编辑更改控制事件添加一个目标,如下所示:

[myTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];


- (void)textFieldDidChange:(UITextField *)sender
{
    NSLog(@"%@",sender.text);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多