I have found this solution to making the next buttons on the ui keyboard go to the next text field, however it is not working at all for me. Is there something I have to do in the storyboard as well? Also, how do I make the next button for the final textfield call the unwind segue? Thank you
//
// AddToDoItemViewController.m
// ToDoList
//
// Copyright (c) 2015 com.example. All rights reserved.
//
#import "AddToDoItemViewController.h"
#interface AddToDoItemViewController ()
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
#property (weak, nonatomic) IBOutlet UITextField *totalTextField;
#property (weak, nonatomic) IBOutlet UITextField *tipTextField;
#property (weak, nonatomic) IBOutlet UIView *singleTableView;
#property (weak, nonatomic) IBOutlet UISwitch *ccSwitch;
#end
#implementation AddToDoItemViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == self.textField) {
[self.totalTextField becomeFirstResponder];
}
else if (textField == self.totalTextField ) {
[self.tipTextField becomeFirstResponder];
}
else{
[textField resignFirstResponder];
}
return YES;
}
/*- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == self.textField) {
[theTextField resignFirstResponder];
} else if (theTextField == self.totalTextField) {
[self.tipTextField becomeFirstResponder];
}
return YES;
}
*/
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
NSLog(#"sender = %#",sender);
if (sender != self.saveButton) return YES;
NSNumberFormatter *formatter1 = [[NSNumberFormatter alloc] init];
NSNumber *totalOrder = [formatter1 numberFromString:self.totalTextField.text];
NSNumber *tipOrder = [formatter1 numberFromString:self.tipTextField.text];
double tot = totalOrder.doubleValue;
double totalOrderWithTip = tipOrder.doubleValue;
if(self.textField.text.length <= 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Field not entered"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}
if(self.totalTextField.text.length <= 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Field not entered"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}
if(self.tipTextField.text.length <= 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Field not entered"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}
if(totalOrder == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Invalid Order Total"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}
if(tipOrder == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Invalid Amount Recieved"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}
if(totalOrderWithTip < tot)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"The amount recieved must be equal to or greater than the order total."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}
return YES;
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if (sender != self.saveButton) return;
if (self.textField.text.length > 0) {
NSNumberFormatter *formatter1 = [[NSNumberFormatter alloc] init];
// NSNumber *tipPercent = [[NSNumber alloc] initWithFloat:0.0];
NSNumber *totalOrder = [formatter1 numberFromString:self.totalTextField.text];
NSNumber *tipOrder = [formatter1 numberFromString:self.tipTextField.text];
NSNumber *actualTip = [[NSNumber alloc] initWithFloat:tipOrder.doubleValue - totalOrder.doubleValue];
double tot = totalOrder.doubleValue;
double tip1 = tipOrder.doubleValue - tot;
self.toDoItem = [[ToDoItem alloc] init];
self.toDoItem.location = self.textField.text;
NSNumber *percent1 = [[NSNumber alloc] initWithDouble:(tip1/tot)*100.0];
if(self.ccSwitch.isOn)
self.toDoItem.isCreditCard = YES;
else
self.toDoItem.isCreditCard = NO;
self.toDoItem.total = totalOrder;
self.toDoItem.tip = actualTip;
self.toDoItem.percentage = percent1;
self.toDoItem.completed = NO;
}
}
#end
In the Connections Inspector for the textField, drag from the "circle" under the section "Outlets" - "delegate", to the View Controller Icon. Or either you can set it in the viewDidLoad method. Some like:
self.textField.delegate = self;
The last textField is closing the keyboard because your are telling the keyboard to resign its first responder condition. Just replace that line for the one that you want to call:
[self shouldPerformSegueWithIdentifier:#"YOUR_IDENTIFIER" sender:your_sender];
And that's it!
Related
I am working on app with a login. What i want to do is that after the login a label displays the username.
Here is my code:
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UITextField *userNameTextField;
#property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Login:(id)sender {
if ([_userNameTextField.text isEqualToString:#""] || [_passwordTextField.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
NSString *strURL = [NSString stringWithFormat:#"http://192.168.1.11:8888/swift/login.php?userName=%#&password=%#",_userNameTextField.text, _passwordTextField.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"1"])
{
NSString *username = _userNameTextField.text;
UILabel *myLabel = (UILabel *)[self.view viewWithTag:100];
myLabel.text = [NSString stringWithFormat:#" Label %#",username];
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:#"logedIn"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
}
else if ([strResult isEqualToString:#"0"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Wrong username / password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Server Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}
#end
Here is a image of my storyboard
In the image you see my first seen in the bottom left corner. the second screen is in the upper right corner. The both have the class ViewController
I am using xcode 7.0
U have 2 different instances of ViewController which means the UITextField that changes in the first one won't be visible to the second one.
U need to have an object (let's call it Model) which will hold the data and change on demand.
Any way, change your architecture to have a Model layer which will hold your data.
If u want to make things works specific here but in bad practice way, create NSString in the AppDelegate and set the data there when changed. And get the data from there on demand.
But again,
change your architecture to have a Model-View-Controller
Set the property for your label in your .h and link it on your storyboard.
#property (nonatomic, strong) IBOutlet UILabel *label;
Then, before presenting your new view controller, you can just set the text for that label.
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:#"logedIn"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
vc.label.text = [NSString stringWithFormat:#" Label %#",username];
[self presentViewController:vc animated:YES completion:NULL];
I have taken an NSString from one class to another
I have a quiz view controller where a user enters a question in a UITextView and then they press next to go to the select friends view controller where they select a user and then send the question over parse.com
quiz.h
#property (nonatomic,strong) IBOutlet UITextView *textField;
#property (nonatomic, strong) NSString *text;
quiz.m
- (IBAction)next:(id)sender {
NSString *text = self.textField.text;
if ([text length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Enter some text"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
sfvc.string = text;
}
}
selectfriendsviewcontroller.h
#property (nonatomic, retain) NSString *string;
selectfriendsviewcontroller.m
#synthezise string;
- (void)viewDidLoad {
[super viewDidLoad];
quizViewController *qvc = [[quizViewController alloc] init];
qvc.text = string;
UITextView *textfield = [[UITextView alloc] init];
string = textfield.text;
}
why does the string show null?? in the quiz.m when i press next the string passes as null, any ideas as to how i can fix?
In quizViewController under next button action
- (IBAction)next:(id)sender {
if ([text length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Enter some text"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
sfvc.string = self.textField.text;
}
}
Then in selectFriendsViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"string %#",self.string);
}
Also check if the outlet of textView is connected to UITextView or not. If not then connect it. And selectFriendsViewController.h , create property #property (nonatomic, strong) NSString *string;
Hope it helps you.
selectfriendsviewcontroller.m
you can access the value of the string from the string property (by the way avoid generic names like string ) also if you use Xcode > 4.4 you can skip #synthezise
in selectfriendsviewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"%#",self.string);
}
I have a simple class like this
.h
#interface DJMyClass : NSObject
+ (void)someFunction;
#end
.m
#import "DJJavaFunction+UIAlert.h"
#interface DJMyClass ()
#property (nonatomic, strong) NSString* someString;
#end
#implementation DJMyClass
+(void)functionWithName:(NSString *)functionName
callbackId:(int)callbackId
args:(NSArray *)args
{
DJMyClass *newFunction = [[DJMyClass alloc] init];
newFunction.function = functionName;
newFunction.callbackId = callbackId;
newFunction.args = args;
[newFunction processFunction];
}
- (void)processFunction
{
[self showAlertWithTitle:title message:message buttons:buttons inputField:inputField callbackId:_callbackId];
}
#end
Now I have created different extensions of this class, which I import and use within this class.
.h
#interface DJMyClass (UIAlert) <UIAlertViewDelegate>
- (void)showAlertWithTitle:(NSString *)title
message:(NSString *)message
buttons:(NSArray *)buttons
inputField:(NSDictionary *)inputField
callbackId:(int)callbackId;
#end
.m
#implementation DJJavaFunction (UIAlert)
- (void)showAlertWithTitle:(NSString *)title
message:(NSString *)message
buttons:(NSArray *)buttons
inputField:(NSDictionary *)inputField
callbackId:(int)callbackId
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
// Add the buttons
for (NSString *btn in buttons)
{
[alert addButtonWithTitle:btn];
}
// Add text field
if (!inputField)
{
alert.alertViewStyle = UIAlertViewStyleDefault;
}
else
{
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *textField = [alert textFieldAtIndex:0];
textField.placeholder = inputField[#"placeholder"];
textField.text = inputField[#"text"];
}
alert.delegate = self;
alert.tag = 44;
[alert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
#end
This all works well, except that the UIAlertViewDelegate methods are never called.
Is it even possible to respond to UIAlertViewDelegate calls from within a category?
Thanks
This question already has an answer here:
Using text field to display an alert [closed]
(1 answer)
Closed 8 years ago.
I asked this question before but for some reason it says closed, but i never got the right answer,can anyone help me add a text field, where if the user types a number in text field once the number reaches the same number as the counter it displays an alert.
#import <UIKit/UIKit.h>
int NumberCount;
#interface ViewController : UIViewController
{
int counter;
IBOutlet UILabel *count;
}
-(IBAction)minus;
-(IBAction)plus;
-(IBAction)zero;
#end
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)plus {
counter=counter + 1;
count.text = [NSString stringWithFormat:#"%i",counter];
}
-(IBAction)minus {
counter=counter - 1;
count.text = [NSString stringWithFormat:#"%i",counter];
}
-(IBAction)zero {
counter=0;
count.text = [NSString stringWithFormat:#"%i",counter];
}
- (void)viewDidLoad {
counter=0;
count.text = #"0";
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I tried adding this in but it didn't work
if (count.text == textField ) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Congrats"
message:#"You met that number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
My ViewController.h :
__weak IBOutlet UITextField *textField;
You are comparing a string with an UITextField object.
You have to compare the count.text string with textField.text string.
Try this:
if ([count.text isEqualToString:textField.text]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Congrats"
message:#"You met that number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
I have implemented in app Email and SMS sending functionality
but i am not being able to send email and SMS. application is crashing
well . . .
i am running it in Simulator
but it should show the AlertView
it's not supposed to crash
My Interface code is as Follows :-
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#interface MessagingVC :UIViewController<MFMessageComposeViewControllerDelegate,MFMailComposeViewControllerDelegate,UITextFieldDelegate,UITextViewDelegate>
- (IBAction)sendEmail:(id)sender;
- (IBAction)sendSMS:(id)sender;
#property (retain, nonatomic) IBOutlet UITextField *EmailToTxtField;
#property (retain, nonatomic) IBOutlet UITextField *PhoneToTxtField;
#property (retain, nonatomic) IBOutlet UITextView *massageBodyTxtView;
#property (retain, nonatomic) NSMutableArray *toRecipentsEmail;
#property (retain, nonatomic) NSMutableArray *toRecipentsPhone;
#property (retain, nonatomic) MFMessageComposeViewController *MessageCompVC;
#property (retain, nonatomic) MFMailComposeViewController *MailCompVC;
#end
MY implementation code is as Follows :-
#import "MessagingVC.h"
#interface MessagingVC ()
#end
#implementation MessagingVC
#synthesize toRecipentsEmail,toRecipentsPhone,MailCompVC,MessageCompVC;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (BOOL)textView:(UITextView *)txtView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if( [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound ) {
return YES;
}
[txtView resignFirstResponder];
return NO;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == _EmailToTxtField)
{
toRecipentsEmail = [NSMutableArray arrayWithArray:[textField.text componentsSeparatedByString:#","]];
}
if (textField == _PhoneToTxtField)
{
toRecipentsPhone = [NSMutableArray arrayWithArray:[textField.text componentsSeparatedByString:#","]];
}
[_EmailToTxtField resignFirstResponder];
[_PhoneToTxtField resignFirstResponder];
NSLog(#"toRecipentsEmail Count == %d",[toRecipentsEmail count]);
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_massageBodyTxtView.delegate = self;
_EmailToTxtField.delegate = self;
_PhoneToTxtField.delegate = self;
toRecipentsPhone = [[NSMutableArray alloc] init];
toRecipentsEmail = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_EmailToTxtField release];
[_PhoneToTxtField release];
[_massageBodyTxtView release];
[toRecipentsEmail release];
[toRecipentsPhone release];
[MailCompVC release];
[MessageCompVC release];
[super dealloc];
}
- (void)viewDidUnload {
[self setEmailToTxtField:nil];
[self setPhoneToTxtField:nil];
[self setMassageBodyTxtView:nil];
[self setToRecipentsEmail:nil];
[self setToRecipentsPhone:nil];
[self setMailCompVC:nil];
[self setMessageCompVC:nil];
[super viewDidUnload];
}
- (IBAction)sendEmail:(id)sender {
self.MailCompVC = [[MFMailComposeViewController alloc] init];
NSString *emailTitle = #"Subject";
MailCompVC.mailComposeDelegate = self;
[MailCompVC setToRecipients:toRecipentsEmail];
[MailCompVC setMessageBody:_massageBodyTxtView.text isHTML:NO];
[MailCompVC setSubject:emailTitle];
[self presentViewController:MailCompVC animated:YES completion:nil];
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Mail cancelled" message:#"Mail cancelled" delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert show];
[alert release];
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Mail saved" message:#"Mail saved" delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert1 show];
[alert1 release];
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"Mail sent" message:#"Mail sent" delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert2 show];
[alert2 release];
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:#"Mail sent failure" message:[NSString stringWithFormat:#"%#",[error localizedDescription]] delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert3 show];
[alert3 release];
break;
default:
break;
}
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)sendSMS:(id)sender {
self.MessageCompVC = [[MFMessageComposeViewController alloc] init];
MessageCompVC.messageComposeDelegate = self;
[MessageCompVC setBody:_massageBodyTxtView.text];
[MessageCompVC setRecipients:toRecipentsPhone];
[self presentViewController:MessageCompVC animated:YES completion:nil];
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
switch (result)
{
case MessageComposeResultCancelled:
NSLog(#"Message cancelled");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message cancelled" message:#"Message cancelled" delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert show];
[alert release];
break;
case MessageComposeResultFailed:
NSLog(#"Message Failed");
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Message Failed" message:#"Message Failed" delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert1 show];
[alert1 release];
break;
case MessageComposeResultSent:
NSLog(#"Message Sent");
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"Message Sent" message:#"Message Sent" delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert2 show];
[alert2 release];
break;
default:
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
when I click on sendEmail button
the application crashes with this output
2013-10-31 12:57:14.095 MyApp[325:c07] toRecipentsEmail Count == 2
2013-10-31 12:57:21.952 MyApp[325:c07] -[__NSMallocBlock__ countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xf2ad5e0
2013-10-31 12:57:21.953 MyApp[325:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSMallocBlock__ countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xf2ad5e0'
*** First throw call stack:
(0x1d65012 0x1a9ce7e 0x1df04bd 0x1d54bbc 0x1d5494e 0x346343 0x346523 0x59fde 0x1ab07055 0x9e42c0 0x9e4258 0xaa5021 0xaa557f 0xaa46e8 0xa13cef 0xa13f02 0x9f1d4a 0x9e3698 0x27d1df9 0x27d1ad0 0x1cdabf5 0x1cda962 0x1d0bbb6 0x1d0af44 0x1d0ae1b 0x27d07e3 0x27d0668 0x9e0ffc 0x2882 0x27b5)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Please Tell me What Am i doing wrong ?
I'm not quite sure whether this is the issue, but from your code, the line
toRecipentsEmail = [NSMutableArray arrayWithArray:[textField.text componentsSeparatedByString:#","]];
which will just return an autoreleased copy of array, so just try
self.toRecipentsEmail = [NSMutableArray arrayWithArray:[textField.text componentsSeparatedByString:#","]] ;
Since you have synthesized the property toRecipentsEmail, doing this will retain a copy of array.