ios 使用`textField:shouldChangeCharactersInRange:`,如何获取包含当前输入字符的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2198067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:51:53  来源:igfitidea点击:

Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?

iosobjective-cuitextfield

提问by user265961

I'm using the code below to try and have textField2's text content get updated to match textField1's whenever the user types in textField1.

我正在使用下面的代码尝试textField2更新 的文本内容以匹配textField1每当用户输入textField1.

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
  if (theTextField == textField1){    
     [textField2 setText:[textField1 text]];    
  }
}

However, the output I observe is that...

但是,我观察到的输出是......

textField2 is "12", when textField1 is "123"

textField2 is "123", when textField1 is "1234"

textField2 为“12”,当 textField1 为“123”时

textField2 为“123”,当 textField1 为“1234”时

... when what I want is:

...当我想要的是:

textField2 is "123", when textField1 is "123"

textField2 is "1234", when textField1 is "1234"

textField2 为“123”,当 textField1 为“123”时

当 textField1 为“1234”时,textField2 为“1234”

What am I doing wrong?

我究竟做错了什么?

回答by Vladimir

-shouldChangeCharactersInRangegets called beforetext field actually changes its text, that's why you're getting old text value. To get the text after update use:

-shouldChangeCharactersInRange文本字段实际更改其文本之前被调用,这就是您获得旧文本值的原因。要在更新后获取文本,请使用:

[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];

回答by btmanikandan

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"%@",searchStr);
    return YES;
}

回答by focorner

Swift 3

斯威夫特 3

Based on the accepted answer, the following should work in Swift 3:

根据接受的答案,以下内容应该适用于Swift 3

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)

    return true
}

Note

笔记

Both Stringand NSStringhave methods called replacingCharacters:inRange:withString. However, as expected, the former expects an instance of Range, while the latter expects an instance of NSRange. The textFielddelegate method uses an NSRangeinstance, thus the use of NSStringin this case.

双方StringNSString有方法叫replacingCharacters:inRange:withString。然而,正如预期的那样,前者期望 的实例Range,而后者期望 的实例NSRange。的textField委托方法使用一个NSRange实例,因此,使用NSString在这种情况下。

回答by tomute

Instead of using the UITextFieldDelegate, try to use "Editing Changed"event of UITextField.

不要使用 UITextFieldDelegate,而是尝试使用 UITextField 的“Editing Changed”事件。

回答by bauerMusic

In Swift(4), without NSString(pure Swift):

在 Swift(4) 中,没有NSString(纯 Swift):

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let textFieldString = textField.text, let swtRange = Range(range, in: textFieldString) {

        let fullString = textFieldString.replacingCharacters(in: swtRange, with: string)

        print("FullString: \(fullString)")
    }

    return true
}

As an extension:

作为扩展:

extension UITextField {

    func fullTextWith(range: NSRange, replacementString: String) -> String? {

        if let fullSearchString = self.text, let swtRange = Range(range, in: fullSearchString) {

            return fullSearchString.replacingCharacters(in: swtRange, with: replacementString)
        }

        return nil
    }
}

// Usage:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let textFieldString = textField.fullTextWith(range: range, replacementString: string) {
        print("FullString: \(textFieldString)")
    }

    return true
}

回答by ioopl

Swift version for it :

Swift 版本:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if string == " " {
        return false
    }

    let userEnteredString = textField.text

    var newString = (userEnteredString! as NSString).stringByReplacingCharactersInRange(range, withString: string) as NSString

    print(newString)

    return true
}

回答by Deepak Danduprolu

This is the code you need,

这是你需要的代码

if ([textField isEqual:self.textField1])
  textField2.text = [textField1.text stringByReplacingCharactersInRange:range withString:string];

回答by ober

use guard

使用警卫

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        guard case let textFieldString as NSString = textField.text where
            textFieldString.stringByReplacingCharactersInRange(range, withString: string).length <= maxLength else {
                return false
        }
        return true
    }

回答by blackjacx

If you need to replace the textfield text with this you can use my solution (Swift 3): https://gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047

如果您需要用这个替换文本字段文本,您可以使用我的解决方案(Swift 3):https: //gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047

After the replacement you can just get textField.textto retrieve the composed text.

替换后,您可以textField.text检索组合文本。

回答by boweidmann

My solution is to use UITextFieldTextDidChangeNotification.

我的解决方案是使用UITextFieldTextDidChangeNotification.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyText:) name:UITextFieldTextDidChangeNotification object:nil];

Don't forget to call [[NSNotificationCenter defaultCenter] removeObserver:self];in deallocmethod.

不要忘记调用[[NSNotificationCenter defaultCenter] removeObserver:self];dealloc方法。