Knowing the complete changed string in textField:shouldChangeCharactersInRange:replacementString:

拜拜、爱过 提交于 2019-12-03 06:34:25

问题


I just asked a question about how to monitor changes to a UITextField and received this response :

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementStr {
    // Enable "Next" if you like what's entered in the replacementStr
}

This works, but the replacement string is not the whole string, just what it is adding. How can I get the whole string? My objective is to see if the string in the text field is blank or equal to a certain number (in different scenarios).

Please note that the outlet to the text field doesn't work in this case, because this method is being called before the text in the field changes.


回答1:


NSString * proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:replacementString];



回答2:


Swift Version

In Swift We need to cast textField's text to NSString. The following can be useful:

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



回答3:


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

//    [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
    NSLog(@"%@",searchStr);
    return YES;
}


来源:https://stackoverflow.com/questions/11605296/knowing-the-complete-changed-string-in-textfieldshouldchangecharactersinranger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!