I have created 2 text Fields (Username and Phone number) when I executed my code, only text1(username) is getting executed. i got alert view, in the same way, i tried to give alert view that is text2(phone number) it must allow numeric numbers,
but in my code unable execute second if statement-text2 (phone number)
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
{
__weak IBOutlet UITextField *text1;
__weak IBOutlet UITextField *text2;
IBOutlet UIAlertView *alert;
}
#property (weak, nonatomic) IBOutlet UITextField *text1;
#property (weak, nonatomic) IBOutlet UITextField *text2;
#property (strong, nonatomic) IBOutlet UIAlertView *alert;
#end
.M
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
{
UIAlertView *prompt;
}
#synthesize text1;
#synthesize alert;
#synthesize text2;
- (void)viewDidLoad
{
[super viewDidLoad];
text1.delegate = self;
text2.delegate=self;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==text1)
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"only number allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
return YES;
}
if (textField==text2)
{
NSLog(#"GOOD day");
NSCharacterSet *myCharSet1 = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
for (int i = 0; i < [string length]; i++)
{
unichar c1 = [string characterAtIndex:i];
if (![myCharSet1 characterIsMember:c1])
{
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"number not allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
}
return YES;
}
#end
You have not set delegate for second textfield. Set delegate of text2 same as text1 as below
- (void)viewDidLoad
{
[super viewDidLoad];
text1.delegate = self;
text2.delegate = self;
}
And for compare UITextField you should use isEqual: instead of = operator. Hence is should be like
if ([textField isEqual:text1]){
.......
Your code here
.......
}
if ([textField isEqual:text2]){
.......
Your code here
.......
}
Change your keyboard type as UIKeyboardTypePhonePad for your phoneTextFeild
phoneTextFeild.keyboardType=UIKeyboardTypePhonePad;
Related
so I'm trying to get a variable containing the name of a PDF file I wish to open in a UIweb View to show up in a label. I first identify the global variable in a seperate class here:
header:
#import <Foundation/Foundation.h>
extern NSString *PDFNameString;
extern NSString *PDFActualName;
#interface GlobalVars : NSObject
{
}
#property (nonatomic, strong) NSString *PDFActualName;
#property (nonatomic, strong) NSString *PDFNameString;
#end
.m:
#import "GlobalVars.h"
NSString *PDFNameString;
NSString *PDFActualName; //the name of the PDF file
#implementation GlobalVars
{
}
#end
then I have the menu where I have an alert dialog featuring a text field so that the user can input the PDF name:
.h
#import <Foundation/Foundation.h>
#import "GlobalVars.h"
#interface TitleViewController : UIViewController{
NSFileManager *FM1;
}
#property (retain, nonatomic) IBOutlet UIBarButtonItem *OpenPDF;
#property (retain, nonatomic) IBOutlet UIBarButtonItem *ViewPDF;
-(void)OpeningPDF;
-(void)alertView;
#end
.m
#import "TitleViewController.h"
#interface TitleViewController ()
#end
#implementation TitleViewController
UIAlertView * alert;
UITextField *textField;
int StopTheAlerts = 0;
- (void)viewDidLoad
{
[super viewDidLoad];
FM1 = [NSFileManager defaultManager];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)ButtonClicked:(id)sender {
self.OpeningPDF;
}
- (void)dealloc {
[_OpenPDF release];
[_ViewPDF release];
[super dealloc];
}
- (void)OpeningPDF
{
StopTheAlerts = 0;
alert = [[UIAlertView alloc]
initWithTitle:#"Please enter a valid PDF name below:"
message:#"(Please add .PDF on the end!) \n \n"
delegate:self cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
textField = [[UITextField alloc] init];
[textField setBackgroundColor:[UIColor whiteColor]];
textField.delegate = nil;
textField.borderStyle = UITextBorderStyleLine;
textField.frame = CGRectMake(15, 90, 255, 30);
textField.placeholder = #"PDF name";
textField.keyboardAppearance = UIKeyboardAppearanceAlert; //set up an alert box with a text field
[textField becomeFirstResponder];
[alert addSubview:textField];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
PDFNameString = textField.text; //set the PDF name variable to the name entered
PDFActualName = textField.text;
NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDir = [Paths objectAtIndex:0];
NSString *TempFilePath = PDFNameString;
PDFNameString = [DocumentDir stringByAppendingPathComponent:TempFilePath];
if([FM1 fileExistsAtPath: PDFNameString]){
_ViewPDF.enabled = true;
}
else {
while(StopTheAlerts <= 0){
UIAlertView *ErrorAlert = [[UIAlertView alloc]
initWithTitle:#"This file dosn't exist!"
message:#"Please reenter the file name!"
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[ErrorAlert show];
[ErrorAlert release];
StopTheAlerts = 1;
}
}
}
#end
This part all works fine, however, when I switch over the the view that contains the UIWebView to actually view the PDF (I've removed that in this part of the code) it has the old "message sent to deallocated instance 0xdb8fca0" error when I try to assign my global variable to the label containing the PDF name, this error also occurs when trying to get the UIWebView to read the PDF using the other global variable.
.h
#import <UIKit/UIKit.h>
#import "GlobalVars.h"
#interface ViewController : UIViewController
#property (retain, nonatomic) IBOutlet UILabel *PDFNameL;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_PDFNameL.text = PDFActualName;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_PDFNameL release];
[super dealloc];
}
#end
If anyone knows a solution to the problem I would be very happy
thanks
I am tryin to pass the user login emial to other view controllers. It is going from a UITextField to a UILabel but it display null when I log in a user. I want it to display the email name in the UILabel field. Any help? here are my files.
vc1.h
#import <UIKit/UIKit.h>
#interface loginUserViewController : UIViewController
#property (nonatomic, strong) IBOutlet UITextField *email;
#property (nonatomic, retain) IBOutlet UITextField *password;
#property (nonatomic, retain) IBOutlet UIButton *login;
#property (nonatomic,retain) IBOutlet UIButton *registerBtn;
-(IBAction)loginUser:(id)sender;
#end
vc2.h
#import <UIKit/UIKit.h>
#import "loginUserViewController.h"
#interface Home : UIViewController
#property (weak, nonatomic) IBOutlet NSString *getEmail;
#property (weak, nonatomic) IBOutlet UILabel *username;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *Nav;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *logout;
-(IBAction)logout:(id)sender;
-(IBAction)bandHome:(id)sender;
#end
vc2.m
import "Home.h"
#import "loginUserViewController.h"
#interface Home ()
#end
#implementation Home
#synthesize getEmail,username, band1, band2, band3;
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
// loginUserViewController *object = [[loginUserViewController alloc]init];
// NSString *string = [[NSString alloc] initWithFormat:#"%#", object.email.text];
username.text = getEmail;
}
vc1.m
#import "loginUserViewController.h"
#import "Home.h"
#import "createBandViewController.h"
#interface loginUserViewController ()
#end
#implementation loginUserViewController
#synthesize email, password;
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidload
{
[super viewDidLoad];
}
-(IBAction)loginUser:(id)sender {
if ([email.text isEqualToString:#""] || [password.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return;
}
NSMutableString *strURL = [[NSMutableString alloc] initWithFormat:#"Pretend reference/login2.php?email=%#&password=%#", email.text, password.text ];
[strURL setString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSMutableString *strResult = [[NSMutableString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"logging in");
if ([strResult isEqualToString:#"1"])
{
NSLog(#"Logged in!");
[self performSegueWithIdentifier:#"login" sender:self];
Home *VC;
VC = [self.storyboard instantiateViewControllerWithIdentifier:#"Home"];
[self.navigationController pushViewController:VC animated:YES];
VC.getEmail = self.email.text;
}else
{
// invalid information
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Invalide Information" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
//email.text = #"";
password.text = #"";
}
-(void)WillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
// Dismisses keyboard by clicking out and hitting return key.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *) textField {
[textField resignFirstResponder];
return YES;
}
#end
vc2.h
#property (weak, nonatomic) IBOutlet NSString *getEmail;
vc2.m
#synthesize getEmail;
-(void)viewDidLoad
{
[super viewDidLoad];
username.text = getEmail;
}
vc1.m
-(IBAction)loginUser:(id)sender {
if ([email.text isEqualToString:#""] || [password.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return;
}
else
{
vc2 *VC;
VC = [self.storyboard instantiateViewControllerWithIdentifier:#"vc2Identifier"];
[self.navigationController pushViewController:VC animated:YES];
VC.getEmail = self.email.text
}
}
You don't need to alloc and init the view controller where you have to get the data , but you have to pass the data from vc1 to vc2 and use the variable of vc2 in vc1 , And what your were doing was using the vc1 value in vc2 . And you were allocating the LoginViewController , and in viewDidUnload method , you have set email textfield as nil . that is why you were getting nil value in vc2
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);
}
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 developed this class that is basically a UIAlertView with an input field that runs on blocks. So, whatever the user does on the alertView (click cancel, ok, or fill the text), returns to a block:
HEADER
typedef void (^onClickBlock)(NSInteger buttonIndex, NSString *textoInput);
#interface AlertViewBlocoComInput : NSObject
- (void)mostrarAlertViewBlocoComTitulo:(NSString *)titulo
mensagem:(NSString *)mensagem
tituloBotaoCancel:(NSString *)tituloCancel
outrosBotoesArray:(NSArray *)titulosOutrosBotoes
inputComPlaceHolder:(NSString *)textoPlaceholder
comBlocoExecucao:(onClickBlock)bloco;
#end
IMPLEMENTATION
#interface AlertComBloco : UIAlertView
#property (nonatomic, copy) onClickBlock runOnClickBlock;
#end
#implementation AlertComBloco
#end
#interface AlertViewBlocoComInput () <UIAlertViewDelegate>
#end
#implementation AlertViewBlocoComInput
- (void)mostrarAlertViewBlocoComTitulo:(NSString *)titulo
mensagem:(NSString *)mensagem
tituloBotaoCancel:(NSString *)tituloCancel
outrosBotoesArray:(NSArray *)titulosOutrosBotoes
inputComPlaceHolder:(NSString *)textoPlaceholder
comBlocoExecucao:(onClickBlock)bloco
{
AlertComBloco *alerta = [[AlertComBloco alloc] initWithTitle:titulo
message:mensagem
delegate:self
cancelButtonTitle:tituloCancel
otherButtonTitles:nil];
alerta.runOnClickBlock =bloco;
// adicionar os outros botões
for (NSString *umOutroBotao in titulosOutrosBotoes) {
[alerta addButtonWithTitle:umOutroBotao];
}
[alerta setAlertViewStyle:UIAlertViewStylePlainTextInput];
UITextField *input = [alerta textFieldAtIndex:0];
input.placeholder = textoPlaceholder;
[alerta show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
AlertComBloco *alerta = (AlertComBloco *)alertView;
onClickBlock bloco = alerta.runOnClickBlock;
UITextField *input = [alertView textFieldAtIndex:0];
if (bloco) {
bloco(buttonIndex, input.text);
}
}
#end
I run it, it shows the alertView with the message, placeholder, perfect. I click cancel or fill the text and press ok and the alertview:clickedButtonAtIndex: is never triggered. I am not seeing why.
thanks
You can directly subclass UIAlertView and add your own initializer. I have abstracted your classes to a single subclass of UIAlertView and it works fine. Please see my posts below,
typedef void (^onClickBlock)(NSInteger buttonIndex, NSString *textoInput);
#interface AlertComBloco : UIAlertView<UIAlertViewDelegate>
#property (nonatomic, copy) onClickBlock runOnClickBlock;
#end
#implementation AlertComBloco
- (id)initWithTitulo:(NSString *)titulo mensagem:(NSString*)mensagem tituloBotaoCancel:(NSString*)tituloCancel outrosBotoesArray:(NSArray *)titulosOutrosBotoes inputComPlaceHolder:(NSString *)textoPlaceholder
comBlocoExecucao:(onClickBlock)bloco{
if(self = [self initWithTitle:titulo message:mensagem delegate:self cancelButtonTitle:tituloCancel otherButtonTitles:nil, nil]){
_runOnClickBlock = bloco;
for (NSString *umOutroBotao in titulosOutrosBotoes) {
[self addButtonWithTitle:umOutroBotao];
}
[self setAlertViewStyle:UIAlertViewStylePlainTextInput];
UITextField *input = [self textFieldAtIndex:0];
input.placeholder = textoPlaceholder;
}
return self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UITextField *input = [alertView textFieldAtIndex:0];
if (self.runOnClickBlock) {
self.runOnClickBlock(buttonIndex, input.text);
}
}
#end
Then, you could call it with the block in your view controller just like this,
- (void)showAlert:(id)sender{
AlertComBloco *alertCombo = [[AlertComBloco alloc] initWithTitulo:#"Hi" mensagem:#"Custom Alert" tituloBotaoCancel:#"Cancel" outrosBotoesArray:#[#"Other"] inputComPlaceHolder:#"Placeholder" comBlocoExecucao:^(NSInteger buttonIndex, NSString *textoInput) {
NSLog(#"Button at index %ld, with text %#", (long)buttonIndex, textoInput);
}];
[alertCombo show];
}
You haven't shown us how you're calling this but most likely your AlertViewBlocoComInput is a local variable that has fallen out of scope and is therefore deallocated before the user completes their input. You can demonstrate this by temporarily adding a dealloc method that will tell you when the object is deallocated.
- (void)dealloc {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
In terms of fixing this, you could make your AlertViewBlocoComInput instance a class property, so it won't be released until you manually nil it. Or you can make AlertViewBlocoComInput maintain a strong reference to itself until clickedButtonAtIndex is called.
Or, easiest, leverage the fact that UIAlertView already retains itself, so you can retire AlertComBloco altogether, folding it into AlertViewBlocoComInput:
typedef void (^onClickBlock)(NSInteger buttonIndex, NSString *textoInput);
#interface AlertViewBlocoComInput : UIAlertView <UIAlertViewDelegate>
- (instancetype)initComTitulo:(NSString *)titulo
mensagem:(NSString *)mensagem
tituloBotaoCancel:(NSString *)tituloCancel
outrosBotoesArray:(NSArray *)titulosOutrosBotoes
inputComPlaceHolder:(NSString *)textoPlaceholder
comBlocoExecucao:(onClickBlock)bloco;
#property (nonatomic, copy) onClickBlock runOnClickBlock;
#end
#implementation AlertViewBlocoComInput
- (instancetype)initComTitulo:(NSString *)titulo
mensagem:(NSString *)mensagem
tituloBotaoCancel:(NSString *)tituloCancel
outrosBotoesArray:(NSArray *)titulosOutrosBotoes
inputComPlaceHolder:(NSString *)textoPlaceholder
comBlocoExecucao:(onClickBlock)bloco
{
self = [super initWithTitle:titulo message:mensagem delegate:self cancelButtonTitle:tituloCancel otherButtonTitles:nil];
if (self) {
self.runOnClickBlock =bloco;
// adicionar os outros botões
for (NSString *umOutroBotao in titulosOutrosBotoes) {
[self addButtonWithTitle:umOutroBotao];
}
[self setAlertViewStyle:UIAlertViewStylePlainTextInput];
UITextField *input = [self textFieldAtIndex:0];
input.placeholder = textoPlaceholder;
}
return self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (self.runOnClickBlock) {
UITextField *input = [alertView textFieldAtIndex:0];
self.runOnClickBlock(buttonIndex, input.text);
}
}
#end
And you'd call it like so:
AlertViewBlocoComInput *obj = [[AlertViewBlocoComInput alloc] initComTitulo:#"title" mensagem:#"message" tituloBotaoCancel:#"OK" outrosBotoesArray:nil inputComPlaceHolder:#"Placeholder" comBlocoExecucao:^(NSInteger buttonIndex, NSString *textoInput) {
// do whatever you want with `buttonIndex` and `textoInput` here
//
// NSLog(#"%ld %#", (long)buttonIndex, textoInput);
}];
[obj show];