Check if any textfield, textview or label changed for a UIViewController..? - iphone

I have a view controller and it contains n number of UITextFields and UItextViews and UILabels, is there anyhow I can get notified if any of them changes..?
I can do it by manually looking at each of them in their respective TextDidChangeNotification and similar but I am looking for a more optimized way of doing this, where I don't have to worry about each of them .

// Assumes you don't use tag values now - if you do small change to create
// and index set, add the ones you use, so all new ones assigned are unique.
// assumes ARC
1) New ivar:
{
NSMutableDictionary *savedValues;
}
1) When you want to baseline the values:
savedValues = [self snapshot];
2) call this to baseline current values initially then at any later point:
- (NSMutableDictionary *)snapshot
{
NSInteger tag = 1;
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[self.view.subviews count]];
for(UIView *v in self.view.subviews) {
if([v isKindOfClass:[UILabel class]] || [v isKindOfClass:[UITextField class]] || [v isKindOfClass:[UITextView class]]) {
if(v.tag == 0) v.tag = tag++; // will happen once
// EDIT below
    [dict setObject:[NSString stringWithString:[(id)v text]] forKey:[NSNumber numberWithInteger:tag]];
}
}
return dict;
}
4) When you want to see if anything changed:
- (BOOL)anyChanges
{
NSDictionary *currentDict = [self snapshot];
return [currentDict isEqualToDictionary:savedValues];
}

You should use one method for all textFields, textView and Labels. and give a unique tag to textFields and textViews and labels. which help you for define it's textField ,textView or Label.
if(sender.tag == 1000)//UILabel
{
UILabel *label=(UILabel *)sender
//write own code for label what do you want.
}
else if(sender.tag == 2000)//UITextField
{
UITextField *textField=(UITextField *)sender
//write own code for textField what do you want.
}
else if(sender.tag == 3000)// UITextView
{
UITextView *textView=(UITextView *)sender
//write own code for textView what do you want.
}

Make your class to handle UIControlEventValueChanged event in your textfield, textview or label's value is changed. Add this line ViewDidLoad method:
[youLabel addTarget:self action:#selector(valueChanged:)
forControlEvents:UIControlEventValueChanged];
// add for textfield, textview also if needed
[youTextField addTarget:self action:#selector(valueChanged:)
forControlEvents:UIControlEventValueChanged];
[youTextView addTarget:self action:#selector(valueChanged:)
forControlEvents:UIControlEventValueChanged];
Now selector would be called when ever value is changed
- (void) valueChanged:(id)sender{
if(sender isKindofClass[UILabel class])
{
//label value changed here to differntiate used tag
if([sender tag] == 0)
....
....
}
else if(sender isKindofClass[UITextField class])
{
// textField value changed to differntiate used tag
if([sender tag] == 0)
....
....
}
else if(sender isKindofClass[UITextView class])
{
// textview value changed to differntiate used tag
if([sender tag] == 0)
....
....
}
}

Related

Adding a method to my uitextfield in cell?

I am adding this Method to my code to format the textfield. I am using the code below to try and add the method, but it not working, what am I doing wrong?
.h file
NSString* phone_;
UITextField* phoneFieldTextField;
#property (nonatomic,copy) NSString* phone;
.m file
#synthesize phone = phone_;
ViewDidLoad{
self.phone = #"";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
// Make cell unselectable and set font.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont fontWithName:#"ArialMT" size:13];
if (indexPath.section == 0) {
UITextField* tf = nil;
switch ( indexPath.row ) {
case 3: {
cell.textLabel.text = #"Phone" ;
tf = phoneFieldTextField = [self makeTextField:self.phone placeholder:#"xxx-xxx-xxxx"];
phoneFieldTextField.keyboardType = UIKeyboardTypePhonePad;
[self formatPhoneNumber:phoneFieldTextField.text deleteLastChar:YES];
[cell addSubview:phoneFieldTextField];
break ;
}
// Textfield dimensions
tf.frame = CGRectMake(120, 12, 170, 30);
// Workaround to dismiss keyboard when Done/Return is tapped
[tf addTarget:self action:#selector(textFieldFinished:) forControlEvents:UIControlEventEditingDidEndOnExit];
}
}
// Textfield value changed, store the new value.
- (void)textFieldDidEndEditing:(UITextField *)textField {
//Section 1.
if ( textField == nameFieldTextField ) {
self.name = textField.text ;
} else if ( textField == addressFieldTextField ) {
self.address = textField.text ;
} else if ( textField == emailFieldTextField ) {
self.email = textField.text ;
} else if ( textField == phoneFieldTextField ) {
self.phone = textField.text ;
}else if ( textField == dateOfBirthTextField ) {
self.dateOfBirth = textField.text ;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* totalString = [NSString stringWithFormat:#"%#%#",textField.text,string];
// if it's the phone number textfield format it.
if(textField.tag == 10 ) {
if (range.length == 1) {
// Delete button was hit.. so tell the method to delete the last char.
textField.text = [self formatPhoneNumber:totalString deleteLastChar:YES];
} else {
textField.text = [self formatPhoneNumber:totalString deleteLastChar:NO ];
}
return false;
}
return YES;
NSLog(#"Testing should change character in range");
}
-(NSString*) formatPhoneNumber:(NSString*) simpleNumber deleteLastChar:(BOOL)deleteLastChar {
if(simpleNumber.length == 0) return #"";
// use regex to remove non-digits(including spaces) so we are left with just the numbers
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[\\s-\\(\\)]" options:NSRegularExpressionCaseInsensitive error:&error];
simpleNumber = [regex stringByReplacingMatchesInString:simpleNumber options:0 range:NSMakeRange(0, [simpleNumber length]) withTemplate:#""];
// check if the number is to long
if(simpleNumber.length>10) {
// remove last extra chars.
simpleNumber = [simpleNumber substringToIndex:10];
}
if(deleteLastChar) {
// should we delete the last digit?
simpleNumber = [simpleNumber substringToIndex:[simpleNumber length] - 1];
}
// 123 456 7890
// format the number.. if it's less then 7 digits.. then use this regex.
if(simpleNumber.length<7)
simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:#"(\\d{3})(\\d+)"
withString:#"($1) $2"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [simpleNumber length])];
else // else do this one..
simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:#"(\\d{3})(\\d{3})(\\d+)"
withString:#"($1) $2-$3"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [simpleNumber length])];
if (simpleNumber.length == 10 && deleteLastChar == NO) { [self resignFirstResponder];}
return simpleNumber;
NSLog(#"Testing format phone number");
}
#pragma mark - TextField
-(UITextField*) makeTextField: (NSString*)text
placeholder: (NSString*)placeholder {
UITextField *tf = [[UITextField alloc] init];
tf.placeholder = placeholder;
tf.text = text ;
tf.autocorrectionType = UITextAutocorrectionTypeNo ;
tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
tf.adjustsFontSizeToFitWidth = YES;
tf.returnKeyType = UIReturnKeyDone;
tf.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
return tf ;
}
The method you are using:
-(NSString*) formatPhoneNumber:(NSString*) simpleNumber deleteLastChar:(BOOL)deleteLastChar
Returns an NSString Object. In your case you are calling the method correctly but you are not setting the Returned NSString object to anything. It is simply hanging there. You need to set the phoneFieldTextField to the formatted text like so:
phoneFieldTextField.text = [self formatPhoneNumber:phoneFieldTextField.text deleteLastChar:YES];
NOTE - If you want to learn more about return methods then read the following:
If you noticed some most methods are of the void type. You know this when you see a method like this:
- (void)someMethod {
int x = 10;
}
What void means is that the someMethod does not return anything to you. It simply executes the code within the method. Now methods than return an object or some other data type look like this:
- (int)returnSomething {
int x = 10;
return x;
}
First thing you will notice is the return type is no longer void, it is an int. This means the method will return an integer type. In this case the code executes and you are returned the value of x.
This is just the start of the topic of return methods but hopefully it makes things a bit clearer for you.
First off you need to tell us What is not working we don't have your app and all your code. You need to explain what is working and what is not working exactly. It took longer then necessary to figure out that your question is why is textField:shouldChangeCharactersInRange: not working. Did you set a breakpoint in the function to see what it was doing. Was it not being called?
That said your bug is that textField:shouldChangeCharactersInRange: is using tags to identify text fields but the rest of the code is using pointers
// if it's the phone number textfield format it.
- if(textField.tag == 10 ) {
+ if(textField.tag == phoneFieldTextField ) {
Also you didn't include the code for makeTextField:placeholder: There could be issues in it too. Compare your code to the makeTextField:placeholder: in my sample.
I created a sample project on GitHub. To fix this. I also demos a better approach to creating input forms using table views.
https://github.com/GayleDDS/TestTableViewTextField.git
Look at both diffs to see what I did to YourTableViewController.m to make things work.
https://github.com/GayleDDS/TestTableViewTextField/commit/d65a288cb4da7e1e5b05790ea23d72d472564793
https://github.com/GayleDDS/TestTableViewTextField/commit/31ecaec8c9c01204643d72d6c3ca5a4c58982099
There is a bunch of other Issues here:
You need to call [super viewDidLoad]; in your viewDidLoad method
You need to correctly indent your code (could be a cut and paste issue)
You should be using the storyboard to create your views. See the better solution tab and BetterTableViewController implementation.
Must Watch - iOS Development Videos
WWDC 2011 - Session 309 - Introducing Interface Builder Storyboarding
https://developer.apple.com/videos/wwdc/2011/?id=309
Stanford iPhone Programing Class (Winter 2013)
Coding Together: Developing Apps for iPhone and iPad
https://itunes.apple.com/us/course/coding-together-developing/id593208016
Lecture 9. Scroll View and Table View
Lecture 16. Segues and Text Fields
Looks like you are not setting the delegate <UITextFieldDelegate> in the .h file, and not assigning your textfield's delegate property to self tf.delegate = self; in order to call - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Try that and let me know how it goes
-Good Luck!
#koray was right: you need to setup the delegate for the class. Your class should be declared as implementing the protocol UITextFieldDelegate (in addition to UITableViewDataSource, I assume)
then in your makeTextField: (NSString*)text placeholder: (NSString*)placeholder method, you need to have something like:
-(UITextField*) makeTextField: (NSString*)text
placeholder: (NSString*)placeholder {
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, 150, 40)];
tf.placeholder = placeholder;
// (...)
tf.delegate = self;
return tf ;
}
Then you need to setup the delegate methods correctly. In the following example, I have a nav bar, since the numbers pad doesn't have a return or a done button. I setup a button that will act as the done button (you may have another way of making the keyboard go, and switching between text fields will trigger the end of edition anyway):
- (void) textFieldDidBeginEditing:(UITextField *)textField {
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneEditing:)];
self.navBar.topItem.rightBarButtonItem = doneBtn;
}
- (void) doneEditing:(id) sender {
if(phoneFieldTextField.isFirstResponder) {
[phoneFieldTextField resignFirstResponder];
}
// (...)
self.navBar.topItem.rightBarButtonItem = nil;
}
Then, the magic happens in the textDidEndEditing delegate method:
- (void)textFieldDidEndEditing:(UITextField *)textField {
if ( textField == phoneFieldTextField ) {
self.phone = [self formatPhoneNumber:textField.text deleteLastChar:YES] ; // convert
[phoneFieldTextField setText:self.phone]; // display
}
// (...)
}

Trouble in making hidden button Visible

Following code i am writing to hide some buttons in viewDidLoad. Here Buttons Are hiding
- (void)viewDidLoad
{
for (int i = 100; i<117; i++)
{
UIButton *smileyButton = (UIButton *)[scroll viewWithTag:i];
UITextField *smileyFields = (UITextField *)[scroll viewWithTag:i];
UIImageView *smileyImage = (UIImageView *)[scroll viewWithTag:i];
smileyFields.hidden = YES;
smileyButton.hidden = YES;
}
}
Now in Following Action am making Buttons Visible. But buttons are not Visible
-(IBAction)editButton:(id)sender
{
for (int i = 100; i<117; i++)
{
UIButton *smileyButton = (UIButton *)[scroll viewWithTag:i];
UITextField *smileyFields = (UITextField *)[scroll viewWithTag:i];
UIImageView *smileyImage = (UIImageView *)[scroll viewWithTag:i];
[smileyFields setHidden:NO]; //TextFields Not Visible
[smileyButton setHidden:NO]; //Buttons Not Visbile
}
}
If you have several views with the same tag, function viewWithTag will return only one view, so if you call this 3 times, you get always the same view.
To do what you want, you could iterate all subviews and check tags:
for (UIView *aView in scrollView.subviews) {
if (aView.tag >= 100 && aView.tag < 117) {
aView.hidden = NO;
}
}
Are you building the view controller in Interface Builder? If so, set the Tag of each thing you want to hide to a different number: try something simple like 1, 2, 3, etc. If you're building in code set the tag property instead. Remember your maximum tag number (let's assume it's 4).
Then add the following to your .h:
- (void)setTaggedViewsHidden:(BOOL)hidden;
and the following to your .m:
- (void)setTaggedViewsHidden:(BOOL)hidden {
for (NSInteger tag = 1; tag <= 4; tag++) {
[scroll viewWithTag:tag].hidden = hidden;
}
}
In your viewDidLoad call it like so:
[self setTaggedViewsHidden:YES];
and in your editButton: selector call it as:
[self setTaggedViewsHidden:NO];
Remember to adjust the code in setTaggedViewsHidden to match the tags you're using. The best way to do this is to #define a constant for the min and max tags and use those in the for loop.

Can't read the segmentedcontroll index

I have implemented several of UISegmentedControl objects before but for one or other reason I am unable to implement it within a tableview cell. I want the user to choose his gender. if the value of the segmentedControl changed a method gets called to save it for further processing.
self.seg = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:#"Man",#"Female", nil]];
[self.seg addTarget:self action:#selector(toggleGender) forControlEvents:UIControlEventValueChanged];
I created the method:
-(void)toggleGender{
NSLog(#"%d",self.seg.selectedSegmentIndex)
if (self.seg.selectedSegmentIndex == 0)
{
NSLog(#"User is a man");
} else if (self.seg.selectedSegmentIndex == 1)
{ NSLog(#"User is a female");
}
}
The first NSLog prints -1 as value if the value has changed.
I declared seg in the header file, and created a property and synthesized it!
I am currently NOT dealllocing this object. (I know this is a memory leak)
Why am I unable to read-out the selected segment, and why does it give back -1 as selected item?
Try this :
self.seg = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:#"Man",#"Female", nil]];
[self.seg addTarget:self action:#selector(toggleGender:) forControlEvents:UIControlEventValueChanged];
(NOTE THE ':' in the #selector..). And change your function by this :
-(void)toggleGender:(id)sender
{
if ([sender isKindOfClass:[UISegmentedControl class]])
{
NSLog(#"%d",[(UISegmentedControl *)sender selectedSegmentIndex]);
if ([(UISegmentedControl *)sender selectedSegmentIndex] == 0)
{
NSLog(#"User is a man");
}
else if ([(UISegmentedControl *)sender selectedSegmentIndex] == 1)
{
NSLog(#"User is a female");
}
}
}

how to find which objects are selected:TRUE from 64 buttons labelled b1, b2 etc

I have a project where there are 64 buttons, you have to click certain ones, then click 'done'. If you clicked the right ones, you get some points, and those then need to disappear.
I have let the user keep track of which buttons are pressed by doing sender setSelected:TRUE.
The first bit is all working fine, but I'd like to be able to then hide the buttons that were selected when the user clicked 'done'.
My current thoughts are:
- what I used in Actionscript to do the same thing was
for (i=1;i++;i<65) {
if(getProperty ("b"+ i, _visible) == true) {do blah blah blah} }
I'm really really really hoping there is an obvious equivalent in objective C that does the same thing?
I definitely do not want to have to go through all 64 buttons and type if ([b1 isSelected == TRUE]etc...
I can't just use sender, as it may be several buttons that have previously been selected that I need to access.
EDIT -
This is now the code that is called when user presses one of the 64 buttons.
-(IBAction) pressed:(id)sender {
UIButton *button = (UIButton *)sender;
if ([sender isSelected] ==FALSE) {
[sender setSelected:TRUE];
}
else {
[sender setSelected:FALSE];
}
if ([myArray containsObject:sender])
{
[myArray removeObject:sender];
}
else {
[myArray addObject:sender];
}
}
This is called when they press the 'done' button.
-(IBAction) checkTotal:(id)sender {
if (total == [(totaltxt.text) intValue]) {
score += 1;
scoretxt.text = [NSString stringWithFormat:#"%i", score];
for (UIButton *b in myArray)
{
[b setHidden:TRUE];
}
[myArray removeAllObjects];
}
else {
// some indication that they pressed the button but were wrong.
}
}
It unfortunately still won't hide the button.
It works if I change it to [n1 setHidden:TRUE] to hide the matching textbox above the button, but won't hide even a specific button -eg- [b1 setHidden:TRUE], let alone all the buttons in my array.
AAAAAAAARGH!!!!
Any ideas?
You can iterate on your view's subviews, and check whether the subview is a button:
for (UIView *view in self.view.subviews)
{
if ([view isKindOfClass: [UIButton class]])
{
// Do processing here
// For instance:
if ((UIButton *)view).isSelected)
view.hidden = YES;
}
}
If you dont want to iterate through all the buttons then how about store a reference to your button in an array then just iterate through that array and clear it when the use clicks done?
-(void)click:(id)sender
{
if([myArray containsObject:sender])
[myArray removeObject:sender];
else
[myArray addObject:sender];
}
-(void)doneClicked:(id)sender
{
for(UIButton *b in myArray)
{
[b setHidden:TRUE];
}
[myArray removeAllObjects]; //whateverr the method is i dont remember it off the top of my head
}
Try [b setAlpha:0.0];
Set the tag when creating the buttons and store the tag index in an array.
-(IBAction) pressed:(id)sender {
}
by sender.tag
then finally run the loop hide all object
and again run loop to unhide the object if it exists in array.

Creating a custom UIKeyBoard for iPhone

If anyone has the app GymBuddy, then they will know what I am talking about. They seem to use the stock Number Pad keyboard but have added a "." button in the lower left as well as a bar across the top to switch to alpha characters. Does anyone know how to do this? Do I make a new view like the keyboard and pull it up and have the buttons correspond to the textField for input? I can't seem to find any information on customizing a keyboard or creating your own. Thanks
I have done this. Basically you add your own button as a subview of the UIKeyboard like this:
// This function is called each time the keyboard is going to be shown
- (void)keyboardWillShow:(NSNotification *)note {
// Just used to reference windows of our application while we iterate though them
UIWindow* tempWindow;
// Because we cant get access to the UIKeyboard throught the SDK we will just use UIView.
// UIKeyboard is a subclass of UIView anyways
UIView* keyboard;
// Check each window in our application
for(int c = 0; c < [[[UIApplication sharedApplication] windows] count]; c ++)
{
// Get a reference of the current window
tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:c];
// Loop through all views in the current window
for(int i = 0; i < [tempWindow.subviews count]; i++)
{
// Get a reference to the current view
keyboard = [tempWindow.subviews objectAtIndex:i];
// From all the apps i have made, they keyboard view description always starts with <UIKeyboard so I did the following
if([[keyboard description] hasPrefix:#"<UIKeyboard"] == YES)
{
// Only add the Decimal Button if the Keyboard showing is a number pad. (Set Manually through a BOOL)
if (numberPadShowing && [keyboard viewWithTag:123] == nil) {
// Set the Button Type.
dot = [UIButton buttonWithType:UIButtonTypeCustom];
// Position the button - I found these numbers align fine (0, 0 = top left of keyboard)
dot.frame = CGRectMake(0, 163, 106, 53);
dot.tag = 123;
// Add images to our button so that it looks just like a native UI Element.
[dot setImage:[UIImage imageNamed:#"dotNormal.png"] forState:UIControlStateNormal];
[dot setImage:[UIImage imageNamed:#"dotHighlighted.png"] forState:UIControlStateHighlighted];
//Add the button to the keyboard
[keyboard addSubview:dot];
// When the decimal button is pressed, we send a message to ourself (the AppDelegate) which will then post a notification that will then append a decimal in the UITextField in the Appropriate View Controller.
[dot addTarget:self action:#selector(sendDecimal:) forControlEvents:UIControlEventTouchUpInside];
return;
}
else if (numberPadShowing && [keyboard viewWithTag:123])
{
[keyboard bringSubviewToFront:dot];
}
else if (!numberPadShowing)
{
for (UIView *v in [keyboard subviews]){
if ([v tag]==123)
[v removeFromSuperview];
}
}
}
}
}
}
- (void)sendDecimal:(id)sender {
// The decimal was pressed
}
Hope that's clear.
-Oscar
Check this post, this could be your answer:
UIKeyboardTypeNumberPad and the missing "return" key