简体   繁体   English

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

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

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 为“12”,当 textField1 为“123”时

textField2 is "123", when textField1 is "1234" textField2 为“123”,当 textField1 为“1234”时

... when what I want is: ...当我想要的是:

textField2 is "123", when textField1 is "123" textField2 为“123”,当 textField1 为“123”时

textField2 is "1234", when textField1 is "1234"当 textField1 为“1234”时,textField2 为“1234”

What am I doing wrong?我究竟做错了什么?

-shouldChangeCharactersInRange gets called before text field actually changes its text, that's why you're getting old text value. -shouldChangeCharactersInRange文本字段实际更改其文本之前被调用,这就是您获得旧文本值的原因。 To get the text after update use:要在更新后获取文本,请使用:

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

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

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 String and NSString have methods called replacingCharacters:inRange:withString . StringNSString都有称为replacingCharacters:inRange:withString However, as expected, the former expects an instance of Range , while the latter expects an instance of NSRange .然而,正如预期的那样,前者需要一个Range实例,而后者需要一个NSRange实例。 The textField delegate method uses an NSRange instance, thus the use of NSString in this case. textField委托方法使用NSRange实例,因此在这种情况下使用NSString

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

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
}

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
}

This is the code you need,这是你需要的代码

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

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
    }

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];不要忘记调用[[NSNotificationCenter defaultCenter] removeObserver:self]; in dealloc method.dealloc方法中。

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.text to retrieve the composed text.替换后,您只需获取textField.text即可检索组合文本。

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

相关问题 使用`textField:shouldChangeCharactersInRange:`,我如何发现字符不匹配? - Using `textField:shouldChangeCharactersInRange:`, how do i found that characters are mismatch? 使用rangeOfString和textfield shouldChangeCharactersInRange-删除字符? - using rangeOfString and textfield shouldChangeCharactersInRange - the delete character? 限制 textField(_:shouldChangeCharactersInRange:replacementString:) 中的字符和字符长度 - Limiting characters and character length in textField(_:shouldChangeCharactersInRange:replacementString:) 如何在Xcode中对键入到TextField中的Integer值进行排序? - How do I sort Integer values typed into a TextField in Xcode? Xcode使用textField shouldChangeCharactersInRange:导致应用崩溃 - Xcode Using textField shouldChangeCharactersInRange: crashes app 如何根据打字文本增加文本字段的宽度? - How to increase width of textfield according to typed text? 如何使用自定义inputView获取UITextFieldDelegate.shouldChangeCharactersInRange? - How can I get UITextFieldDelegate.shouldChangeCharactersInRange to fire with custom inputView? 如何将文本编程到文本字段中? - How do I program text into textfield? textField:shouldChangeCharactersInRange:replacementString:in subclass - textField:shouldChangeCharactersInRange:replacementString: in subclass Textfield应该迅速改变字符范围 - Textfield shouldchangecharactersinrange swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM