All I want to do, If there is nothing on UITextField , application will show an alert. I don't understanding what's wrong I'm doing. here is my code:
- (IBAction)Calculate:(id)sender {
/*If there is nothing on textfield, it will show an alert*/
if ([addtake.text length] && [Subtake.text length] == 0)
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert"message:#"Empty TextField not allowed" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil];
[myAlert show];
}
else{
NSString *Adding =[addtake text];
NSInteger number = [Adding intValue]; /*Converting String to int*/
NSInteger new = 5 + number;
NSString *newString = [NSString stringWithFormat:#"%d",new];
[myAdd setText:newString];
/*Subtruct*/
NSString *Subtruct =[Subtake text];
NSInteger SubNumber = [Subtruct intValue];
NSInteger newSub = 10 - SubNumber;
NSString *newSubString = [NSString stringWithFormat:#"%d",newSub];
[mySub setText:newSubString];
[addtake resignFirstResponder];
[Subtake resignFirstResponder];
}
}
Try making each sub-clause in your if statement explicit - if only for readability...
I would use logical OR, not logical AND in your test. So that if either text field is empty the alert would show
if ((![addtake.text length]) || (![Subtake.text length]))
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert"message:#"Empty TextField not allowed" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil];
[myAlert show];
}
if ([addtake.text length] == 0 && [Subtake.text length] == 0)
I assume that addText is your tesxField so you need to set the condition [addtake.text length] == 0 aswell.
Related
I want to check if the text inserted in a textfield is also in my NSMutableArray.
So let's say my NSMutableArray has these objects: "Hey, Hello, No, Yes".
Then when a user enters the text: "Hello" i want there to appear a UIAlertView. I now have the following:
for (int slt = 0; slt < [zouten count]; slt++) {
if (zout.text = [zouten objectAtIndex:slt]) {
alert = [[UIAlertView alloc]initWithTitle:#"Goedzo!" message:[NSString stringWithFormat:#"Je hebt een zout gevonden"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
}
[alert show];
But somehow the message appears with every word. what am i doing wrong?
When you compare like this:
if (zout.text = [zouten objectAtIndex:slt])
you are actually assigning instead of comparing so it will be TRUE always.Therefore instead of using =, you should compare like this:
if ([zout.text isEqualToString:[zouten objectAtIndex:slt]])
Your code should be:
for (int slt = 0; slt < [zouten count]; slt++) {
if ([zout.text isEqualToString:[zouten objectAtIndex:slt]]) {
alert = [[UIAlertView alloc]initWithTitle:#"Goedzo!" message:[NSString stringWithFormat:#"Je hebt een zout gevonden"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
break;
}
}
You can use isEqualToString method to compare strings.
if([zout.text isEqualToString:[zouten objectAtIndex:slt]])
Alternatively you could make your code more concise by converting to a set and checking for the entry, e.g.
NSSet *set = [NSSet setWithArray: zouten];
if([set containsObject:zout.text]) {
...
}
I have iphone app in which i enter any number value like 10 2 0 1 0.2 etc i want that instead of this if user enter any text it should alert that enter a number.
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Value Must Be In Number " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
try this code:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField==txtMobileNo)
{
[self validatePhone];
}else
{
[textField resignFirstResponder];
}
// called when 'return' key pressed. return NO to ignore.
return YES;
}
- (BOOL) validatePhone
{
NSString *phoneRegex = #"^+(?:[0-9] ?){6,14}[0-9]$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
if ([phoneTest evaluateWithObject:txtMobileNo.text] == YES)
{
NSLog(#"proper phone nO ");
return YES;
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:#"Please,Enter Your Person proper phone no" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil ];
[alert show];
[alert release];
NSLog(#"phone no. not in proper format");
return NO;
[txtMobileNo becomeFirstResponder];
}
}
I hope you helpful.
That disrupts the app kind of, doesn't it? What you want to look at is the UITextfield delegate methods. Set your viewController as the textields delegate and make it respond o UITextFieldDelegate protocol.
I would implement the textField:shouldChangeCharactersInRange:replacementString method and check the replacementString for unwanted characters.
But rather than displaying an alert, I guess I would just return NO if unwanted characters are contained there. Then, when the user enters something other than what you want, nothing happens.
you can check if it is a number using the following:-
NSString *yourString= #"121212";
NSCharacterSet *decimalNUmSet= [NSCharacterSet decimalDigitCharacterSet];
BOOL isNum= ([[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#""] ||
[[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#"."]);
here the second part includes decimal numbers also.
the other way is to present a numeric keyboard to user so that he can type only numbers.
You validate the entered character and do your logic in this delegate ,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// your logic to restriction goes here.like check the entered char and through alert
}
-(BOOL) validateNumericValue:(NSString*) textValue
{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:textValue];
if (number != nil)
{
return YES;
}
return NO;
}
I'm currently working in Xcode on an iOS app...
I've set up a UIAlertView (with a question as the message ) to pop up with a text field to retrieve a response.
The desired functionality is that upon entering an incorrect value into the text field, the UIAlert would loop... Until the correct response is entered. At this point, the UIAlert would be dismissed.
Heres what I have so far...
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSString* correctAnswer = #"2";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Alarm"
message:#"1 + 1 ="
delegate:self
cancelButtonTitle: nil
otherButtonTitles:#"Continue", nil ];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField* answerField = [alert textFieldAtIndex:0];
answerField.keyboardType = UIKeyboardTypeNumberPad;
answerField.placeholder = #"answer";
[alert show];
// I feel like this would work, but I know it doesn't...
NSString *answerFieldString = answerField.text;
if ([answerFieldString isEqualToString: correctAnswer ])
{
[alert dismissWithClickedButtonIndex:-1 animated:YES];
}
}
I've done extensive google searching and can't come up with a solution... Any responses would be much appreciated!
try this...
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *answerFieldString = answerField.text;
if ([answerFieldString isEqualToString: correctAnswer ])
{
[alertView dismissWithClickedButtonIndex:-1 animated:YES];
}
}
I am trying to detect whether a NSNumber is between 0 and 255 or not. Whenever I run the app, I receive the alert view that my number is greater than 255, even when it is not. I do not have this problem with 0.
if (redValue < 0) {
NSLog(#"Red value is less than 0");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Your number must be greater than 0." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
} else if (redValue > 255) {
NSLog(#"Red value is greater than 255");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Your number must be less than 255." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
Additionally, I receive this warning on the "else if (redValue > 255)" line: Ordered comparison between pointed and integer ('NSNumber *' and 'int'), So I'm assuming I have to convert this NSNumber to an integer?
Should be:
if([redValue intValue] < 0) {
...
if([redValue intValue] > 255) {
...
Assuming it is an int. If it isn't go to the NSNumber Class Reference look under "Accessing Numeric Values" and replace intValue with the appropriate thing.
use intValue to get the number as an int:
[redValue intValue]
try this
[redValue intValue] > 255
if (redValue.intValue >255)
{
// it's greater than 255
}
I have a UISegmentControl that select nothing through IB, after the user selects the segment it becomes selected. How do i do it so that it doesnot gets selected?
//Show question method
-(void)question:(NSInteger)i
{
// Path to the plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Question" ofType:#"plist"];
// Set the plist to an array
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//Check the number of entries in the array
NSInteger numCount = [array count];
if(i <numCount)
{ NSDictionary *dict = [array objectAtIndex:i];//load array index 0 dictionary data
self.title = [NSString stringWithFormat:#"Question %d", i+1];//set the nav bar title
quest.text = [dict valueForKey:#"Question"];//Set the Question to storage
ans.text = [dict valueForKey:#"Answer"];//Set the Answer to storage
NSInteger option = [[dict valueForKey:#"NumberOfOption"] integerValue ];//Check options to determine the question type
//check if the option is is a QRCode or Multiple Choices Question
if (option ==0)
{
QRbutton.alpha = 1; //show the QR Code Button If there is no options
OptionsAnswer.alpha = 0;//Hide Option if there is no options
}
else
{
QRbutton.alpha = 0.0;//Hide QR Code Button if there is options
OptionsAnswer.alpha = 1;//Show Option if there is options
[OptionsAnswer setTitle:[dict valueForKey:#"Option1"] forSegmentAtIndex:0];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option2"] forSegmentAtIndex:1];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option3"] forSegmentAtIndex:2];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option4"] forSegmentAtIndex:3];//Set Option Answer Value
[OptionsAnswer addTarget:self action:#selector(OptionAnswerCheck) forControlEvents:UIControlEventValueChanged];//Call action when options is being selected
}
}
else {
//if question is all answered, it will prompt an alert for end game video.
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Well Done"
message:#"You Have Answered All The Questions, Oh Wait A Minute I Heard A Cracking Sound...." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
}
//Check if the selected Option is correct
-(IBAction)OptionAnswerCheck
{
//define a persistant location to save which question has been answered
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];//question storages
//pass the value from the selected option to a string
//NSString * selectedTitle = ([OptionsAnswer selectedSegmentIndex] >= 0) ? [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]] :
NSString * selectedTitle = [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]];
NSLog(#"Selected Title = %#",selectedTitle);//test
//check if the selected value is equal to the answers
if ([selectedTitle compare:self.ans.text] ==NSOrderedSame)
{
//Popup to say answer Correct
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Correct!"
message:#"Nice Work, Lets Move On To The Next Question" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
//increase the question number
[self question:++currentQuestion];
//save increased question
[userDefaults setInteger:currentQuestion forKey:#"currentQuestion"];
}
else
{
//Popup to say answer Wrong
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Incorrect"
message:#"Close! But That's Not Right, Try Another Answer" delegate:nil
cancelButtonTitle:#"Try Again." otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
//OptionsAnswer.selectedSegmentIndex = UISegmentedControlNoSegment;
}
Just search for setMomentary: in your developer documentation inside Xcode.
I'm not entirely sure what you're asking here, but I think that you want to set the momentary property toYES.
The property is in the inspector of IB as well. (Can't post a screenshot, I'm on my iPhone).