Is that integer equal to the number in textfield - ios

I'm new to Xcode and Objective-C. I watched a tutorial where he compared a char with the entered text in the textfield of the simulator. He used the following code:
BOOL isUsersEqual = [self.username isEqualToString:[self.usernameTextField text]];
When trying to build a small app myself I have problems to get the number out of the Textfield and be processed into my code. I want it to compare the random number I generated to the number in the textfield. How can I accomplish that?
I know this is kind of a nooby question and I don't wanna ask every time. Is there someplace I can look up all those types of questions?

You can try it by converting the number into string and then comparing -
NSString *number = [self.username stringValue];
if(number isEqualToString:self.usernameTextField.text){
//Do Something
}
else{
//Do Something
}
But this method only works when you're comparing Equals To -
For Greater than/ Less than/Equal to you can try it by converting the textfield's text into number and then comparing -
NSNumber *number = [self.usernameTextField.text integerValue];
if(number == self.username){
//Do Something
}
else{
//Do Something
}

To compare your generated number with a number from textField, you must first typecast the textField text to NSInteger using
NSInteger b = [[textField text] integerValue];
then you can proceed to compare the 2 numbers.
To fully understand these types of questions, I recommend you learning about objective-c primitive types and typecasting. Good luck!

Related

How to limit UILabel text using objective C?

I have created Tableview cell with custom UILabel. For this UILabel data, I am loading from NSMutableArray. NSMutableArray data loading from JSON. Now the problem is I need to limit the tableview cell UILabel text. Here below one example
Now :
-------------------------
12.132454556
-------------------------
Needed :
-------------------------
12.13
-------------------------
My Code :
pointbl.text = [NSString stringWithFormat:#"%#",[arraydata objectAtIndex:indexPath.row]];
Above tableview cell label data I need to show 5 digits only including ".". Some times NSMutableArray value will come "null", So based on that also I need to make some solution.
I have tried by using below code but, If my value "null" then its throwing exceptions.
temp = [[arraydata objectAtIndex:indexPath.row]stringValue];
if ([temp length] > 5) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 5}];
temp = [temp substringWithRange:range];
}
The simplest solution would be to add temp != nil to the if statement.
However, you may implement this in a different way. What's the type of the objects that are saved in arraydata? If's it a float value (and not a string, as can be concluded from your code samples), you can simply use NSNumberFormatter for the display. Even simpler, you can use: [NSString stringWithFormat:#"0.2f", floatValue] and it will give you at least most of what you're looking to achieve.
Try to convert to float:
if ([arraydata objectAtIndex:indexPath.row] != nil) {
pointbl.text = [NSString stringWithFormat:#"%.2f%%",[[arraydata objectAtIndex:indexPath.row]floatValue]];
}
else {
pointbl.text = #"0";
}
// as you are loading values from json so, it can have "null" value ("null" in string format, different from nil if object is empty)
float a = [yourValue floatValue];
label.text = [NSString stringWithFormat:#"%.2f",a];

Adding label text together

Hi im relatively new to iOS and I'm just wondering how i would add two labels together.
- (IBAction)switch1
{
if (switch1.on) {
value1.text = #"3";
} else {
value1.text = #"0";
}
}
- (IBAction)switch2
{
if (switch2.on) {
value2.text = #"3";
} else {
value2.text = #"0";
}
}
As you can see i have used two switches which would show two different values if they were turned on or off.
Could someone help me understand how i would add two values together.
I.e if switch one was on and switch two was off the value would be three i want this value to be shown in another label.
So far i have come up with this but for some reason it doesn't work, i have a feeling it is the format specifier but I'm not sure.
int sum = [[value1 text] intValue] + [[value2 text] intValue];
value3.text = [NSString stringWithFormat:#"%d", sum];
Dont you have this:
int sum = [[value1 text] intValue] + [[value2 text] intValue];
value3.text = [NSString stringWithFormat:#"%d", sum];
in ViewDidLoad or something? Because you have to call this at the end of both IBActions. If you don't, your final value will never change.
Make sure you properly created an outlet connection in Interface Builder as described here:
Creating an Outlet Connection
In short words. Ctrl+Click & Drag from the UISwitch to File’s Owner and click the new switch1 or switch2 action. Create outlets for the text fields and switches and link them.
Set breakpoints in switch1 and switch2 methods and ensure there are being called.
Use po command in the console to check if the text fields and switches are configured correctly.
For example:
po _textField1
should print text field's description. It will print nil when the text field is not there - not linked to a control in interface builder.

Showing a correct answer when someone selects a wrong one

Okay so I am new to objective-c and have used a couple different tutorials to build my first app that is a quiz. I had it completely done and I was somewhat satisfied.. then I realized that if someone selects the wrong answer it doesn't show them what the correct one is. So I have been trying to figure it out for a little bit. So I created a new label That stays hidden until an answer is chosen.
Is there an if statement I can use that can utilize the text I set buttons to? For example:
switch (QuestionSelected) {
case 0:
QuestionText.text = [NSString stringWithFormat:#"Question One"];
[Answer1 setTitle:#"Answer number 1" forState:UIControlStateNormal];
[Answer2 setTitle:#"Answer number 2" forState:UIControlStateNormal];
[Answer3 setTitle:#"Answer number 3" forState:UIControlStateNormal];
[Answer4 setTitle:#"Answer number 4" forState:UIControlStateNormal];
Answer1Correct = YES;
break;
This is what a question looks like within the category. My Answer1-4's are the buttons. And the Answer1Correct (depending on the answer) is a BOOL statement.
Is there a line that I can use in an if statement saying something along
if (Answer1Correct == YES) {
CorrectAnswer.text = [NSstring stringWithFormat:"#?", Answer1]; (The question mark would be for text the button was set to. I know that #i, can be used for integers but I don't know if I can use the text a button was set to)
I know that won't work but I am trying to wrap my head around how a lot of the valuables work. For instance, the problem I see is that within my questions I have BOOLs, and the only way it activates the BOOL is dependent on what they choose. For instance if they chose Answer2 in that previous statement it just sets runs my wrong answer one because this is what I have for the buttons
-(IBAction)Answer1:(id)sender{
if (Answer1Correct == YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
And then the same thing for the following three buttons.
I know I am probably all over the place but the reason I started this was to try and learn how to understand it. So how can I establish what is Correct when they choose the wrong one and how could I make the label show accordingly. I am not asking to be spoon fed, this is my first fully functional app that doesn't really have a full purpose other than myself trying to put things together and understand how things work together. So a little explanation or where I can read up on what is going on would be more appreciated then just an answer. I probably need to give a little more information so if I what I am asking doesn't make sense please ask. Thank you guys for the help.
Without seeing all of the code it's difficult, however one approach would be to have an array with the correct values in for each of the questions you would need to set a strong reference to this to ensure that it's not dealloc'd by arc.
in your .h
#property (nonatomic, strong)NSArray *correctAnswersArray;
#property (nonatomic, strong) IBOutlet UILabel *myLabelForIncorrectAnswer;
in your .m
-(void)viewDidLoad{
self.correctAnswersArray = [[NSArray alloc]initWithObjects:#"answer one", #"answer two", #"answer three", #"answer four",nil];
}
this can be reference using
self.correctAnswersArray[i];
where 'i' is the int value you require from the array - note that arrays are indexed starting at 0
With regards to your current conditional statement, you could set the label text using the array when you confirm if the answer is correct or incorrect so
if (Answer1Correct == YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
self.myLabelForIncorrectAnswer.text = self.correctAnswersArray[0];
}
and so on for each of the conditionals amending the array index number for each 'else' condition

Calculating numbers in UITextField

This may be a very easy question for some of you, but I really would appreciate some help. I am trying to divide one UITextField number by another and when you push the button, it displays it in the third UITextField. Here's what I have so far but get the Invalid operands to binary expression (UITextField *' and 'UITextField *') error.
and yes, i know this is a very simple question, but an answer would really help me. Thanks!
- (IBAction)calculateButton:(id)sender;
{
kdField = firstNum / secondNum;
}
As you can see, I'm trying to set the third UITextField to the firstNum / secondNum when the user presses the calculateButton
Assuming kdField is your UITextField:
kdField.text = [NSString stringWithFormat:#"%d",(firstNum/secondNum)];//or use %f if you're dividing floats
Additionally, if firstNum and secondNum are in UITextFields you'd have to grab the int values with something like:
NSString *firstNumString = firstNumField.text;
int firstNum = [firstNumString intValue];
I Assume KdField, FirstNum and secondNum are all global UITextfield.
Remove the semi-colon after (id)sender
In your buttonAction try something like this:
- (IBAction)calculateButton:(id)sender{
kdField.text = [NSString stringWithFormat:#"%f",[firstNum.text intValue] / [secondNum.text intValue]];
}
I put %f since division can have decimal places

UISearchBar that Ignores Special Characters when Searching UITableView Cell

Thanks to the help of those on SO, I have a great UISearchBar that filters my UITableView. There is one more feature that I'd like to add.
I would like the UISearchBar filter to ignore special characters like apostrophes, commas, dashes, etc... and to allow cells with text like "Jim's Event" or "Jims-Event" to still come up if the user types "Jims Event".
for (NSDictionary *item in listItems)
{
if ([scope isEqualToString:#"All"] || [[item objectForKey:#"type"]
isEqualToString:scope] || scope == nil)
{
NSStringCompareOptions opts = (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch);
NSRange resultRange = [[item objectForKey:#"name"] rangeOfString:searchText
options:opts];
if (resultRange.location != NSNotFound) {
[filteredListItems addObject:item];
}
}
}
Anyone have any ideas? Thank you!
This one is a little tricky. The first solution that comes to mind is to strip any character that you deliberately don't want to match from both the search and item strings, then do the comparison. You can use NSCharacterSet instances to do that filtering:
// Use this method to filter all instances of unwanted characters from `str`
- (NSString *)string:(NSString *)str filteringCharactersInSet:(NSCharacterSet *)set {
return [[str componentsSeparatedByCharactersInSet:set]
componentsJoinedByString:#""];
}
// Then, in your search function....
NSCharacterSet *unwantedCharacters = [[NSCharacterSet alphanumericCharacterSet]
invertedSet];
NSString *strippedItemName = [self string:[item objectForKey:#"name"]
filteringCharactersInSet:unwantedCharacters];
NSString *strippedSearch = [self string:searchText
filteringCharactersInSet:unwantedCharacters];
Once you have the stripped strings, you can do your search, using strippedItemName in place of [item objectForKey:#"name"] and strippedSearch in place of searchText.
In your example, this would:
Translate the search string "Jims Event" to "JimsEvent" (stripping the space)
Translate an item "Jim's Event" to "JimsEvent" (stripping the apostrophe and space)
Match the two, since they're the same string
You might consider stripping your search text of unwanted characters once, before you loop over item names, rather than redoing the same work every iteration of your loop. You can also filter more or fewer characters by using a set other than alphanumericCharacterSet - take a look at the class reference for more.
Edit: we need to use a custom function to get rid of all characters in the given set. Just using -[NSString stringByTrimmingCharactersInSet:] only filters from the ends of the string, not anywhere in the string. We get around that by splitting the original string on the unwanted characters (dropping them in the process), then rejoining the components with an empty string.

Resources