How to know whether a UITextField contains a specific character
-
12-09-2019 - |
Question
How would I say that if a UITextField has @"-" in it, do something. Right now my code is like this. It doesn't seem to work:
if (MyUITextField.text == @"-") {
NSRange range = {0,1};
[a deleteCharactersInRange:range];
MyUITextField.text = MyUILabel.text;
}
I know that I am doing something very wrong with the code. Please help.
Solution
try changing ==
to [MyUITextField.text isEqualToString:@"-"]
as == tests to see if they are the same object, while isEqualToString compares the contents of the strings.
OTHER TIPS
Assuming your string is defined as:
NSString *str = @"foo-bar";
To check if your string contains "-" you can do the following:
if ([str rangeOfString:@"-"].length > 0)
{
NSLog(@"Contains -");
}
It looks like you wanted to delete the first character if a string starts with a given character. In this case you can do something like this:
if ([str hasPrefix:@"f"])
{
NSLog(@"Starts with f");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow