detect where and what changes within textfield

杀马特。学长 韩版系。学妹 提交于 2019-12-12 04:56:52

问题


How can I check what exactly and where a string changed in my textfieldDidChange method?

let str1 = "Hello how are you @Marie, nice day uh?"

So imagine my user decides to edit the text and link markus instead of marie

let str2 = "Hello how are you @ Markus, nice day uh?"

I need a method that detect the change of @ Markus in the text field but doesn't change anything else in the string. I am able to detect last word, first word and so one, but its important to also see what changed within the text

i am thinking about a method that

a = "Hello how are you"
b = newly changed text field
c = ", nice day uh?"

let str3 = a + b + c // More or less 

Maybe that I get the index where I am editing at, taking the word out at this index - from left space to right space - and cutting it out? Thanks in advance, yes I am a beginner :P


回答1:


If you set your view controller up to be the delegate of your text field, you can implement the textField(_:shouldChangeCharactersIn:replacementString:) delegate method. That will tell you the range of characters that the user has asked to change, as well as providing the replacement string.

You could use that to monitor the user's edits. However, the string can easily get changed in a way that is difficult to track. What if the user deletes the "Hello how are you " part? What if they replace the whole string with "Shut your festering gob @fred, you malodorous pervert"?

You're probably better off getting the whole string from the text field and parsing it. You could accept anything the user enters, an look for and @ sign, and take everything after that until the next space as the name, e.g.@alphanumerics`

Edit:

Alternately, you could set up your screen so the first part is a label, the middle part is an editable text field, and the last part is another label. The only part the user is able to edit is the middle part, the name. Or you could make it 3 separate text fields, the prefix, the name, and the suffix. Tell the user what you expect them to enter into each part.




回答2:


You can split your string using this code.

For Objectve c :

1. Create function like this.

 -(NSString *)checkString:(NSString *)splitString{

            NSRange firstObj = [splitString rangeOfString:@"@"];
            NSRange secondObject = [splitString rangeOfString:@","];
            NSRange rangeSubStr = NSMakeRange(firstObj.location + firstObj.length, secondObject.location - firstObj.location - firstObj.length);
            return [splitString substringWithRange:rangeSubStr];
 }

2. Use this function like this.

[self checkString:@"Hello how are you @Marie, nice day uh?"]

Then every change in text, you can check substrings, and compare them to original substrings.



来源:https://stackoverflow.com/questions/46085704/detect-where-and-what-changes-within-textfield

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