UISlider in xcode - objective-c

I was wondering if anyone has any idea how to connect a text field with a slider. I want the slider to list numbers from 1-100 or 1-1000. I've looked places but there is no true answer to what I'm looking for. Your help would be greatly appreciated

ViewController.h
#interface ViewController : UIViewController {
IBOutlet UISlider *mySlider;
IBOutlet UITextField *myTextField;
}
#property (nonatomic, retain) IBOutlet UISlider *mySlider;
#property (nonatomic, retain) IBOutlet UITextField *myTextField;
- (IBAction) sliderValueChanged:(id)sender;
- (IBAction) changeButtonPressed:(id)sender;
ViewController.m
#import "ViewController.h"
#implementation TutorialProjectViewController
#synthesize mySlider, myTextField;
- (void)viewDidLoad {
[super viewDidLoad];
self.myTextField.delegate = self;
}
- (IBAction) sliderValueChanged:(UISlider *)sender {
myTextField.text = [NSString stringWithFormat:#" %.1f", [sender value]];
}
- (IBAction) changeButtonPressed:(id)sender {
NSString *textValue = [myTextField text];
float value = [textValue floatValue];
if (value < 0) value = 0;
if (value > 100) value = 100;
mySlider.value = value;
myTextField.text = [NSString stringWithFormat:#"%.1f", value];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[myTextField resignFirstResponder];
//[put your textfield name here resignFirstResponder];
return NO;
}
#end
Change Slider Value:

I'm assuming you want to update the text field's text as the slider is changed.
You don't connect the two. You need to listen for changes to the slider's value. In the method that you setup for this, you need to convert the slider's value to the text you want. You then update the text field's text with this new text based on the slider's value.
The hook for the slider:
[someSlider addTarget:self action:#selector(sliderUpdate:) forControlEvents:UIControlEventValueChanged];
The method that listens to the slider:
- (void)sliderUpdate:(UISlider *)slider {
float newVal = slider.value;
NSString *newText = [NSString stringWithFormat:#"%d", (int)newVal];
someTextField.text = newText;
}
This code assumes the slider is referenced in the someSlider ivar and the text field is referenced by the someTextField ivar. It also assumes the slider's minimumValue is 0 and the maximumValue is 100 or 1000 as needed.

#import "FirstViewController.h"
#interface FirstViewController ()
#property (weak, nonatomic) IBOutlet UITextField *myTextBox;
#property (weak, nonatomic) IBOutlet UISlider *mySlider;
#property (weak, nonatomic) IBOutlet UINavigationBar *titleOnTop;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *backButton;
- (IBAction)changeGreeting:(id)sender;
- (IBAction)sliderValueChanged:(id)sender;
- (IBAction)changeButtonPressed:(id)sender;
#end
#implementation FirstViewController
#synthesize mySlider, myTextBox;
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTextBox.delegate = self;
}
- (IBAction) sliderValueChanged:(UISlider *)sender
{
myTextBox.text = [NSString stringWithFormat:#"%.1f", [sender value]];
}
- (void)sliderUpdate:(UISlider *)slider {
float newVal = slider.value;
NSString *newText = [NSString stringWithFormat:#"%d", (int)newVal];
myTextBox.text = newText;
}
- (IBAction) changeButtonPressed:(id)sender
{
NSString *textValue = [myTextBox text];
float value = [textValue floatValue];
if (value < 0) value = 0;
if (value > 1000) value = 1000;
mySlider.value = value;
myTextBox.text = [NSString stringWithFormat:#"%.1f", value];
if ([myTextBox canResignFirstResponder]) [myTextBox resignFirstResponder];
}
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
if (myTextBox)
{
if ([myTextBox canResignFirstResponder]) [myTextBox resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (IBAction)changeGreeting:(id)sender {
self.username = self.myTextBox.text;
NSString *nameString = self.username;
if ([nameString length] == 0) {
nameString = #"World";
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[myTextBox resignFirstResponder];
return YES;
}
#end

#import "FirstViewController.h"
#interface FirstViewController ()
#property (weak, nonatomic) IBOutlet UITextField *myTextBox;
#property (weak, nonatomic) IBOutlet UISlider *mySlider;
#property (weak, nonatomic) IBOutlet UINavigationBar *titleOnTop;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *backButton;
- (IBAction)changeGreeting:(id)sender;
- (IBAction)sliderValueChanged:(id)sender;
- (IBAction)changeButtonPressed:(id)sender;
- (IBAction)backgroundTouched:(id)sender;
- (IBAction)textFieldReturn:(id)sender;
#end
#implementation FirstViewController
#synthesize mySlider, myTextBox;
- (IBAction)backgroundTouched:(id)sender;
{
[myTextBox resignFirstResponder];
}
- (IBAction)textFieldReturn:(id)sender;
{
[sender resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTextBox.delegate = self;
}
- (IBAction) sliderValueChanged:(UISlider *)sender
{
myTextBox.text = [NSString stringWithFormat:#"%.1f", [sender value]];
}
- (void)sliderUpdate:(UISlider *)slider {
float newVal = slider.value;
NSString *newText = [NSString stringWithFormat:#"%d", (int)newVal];
myTextBox.text = newText;
}
- (void)textFieldDidChange:(UITextField*)sender { slider.value = [sender.text floatValue]; }
- (IBAction) changeButtonPressed:(id)sender
{
NSString *textValue = [myTextBox text];
float value = [textValue floatValue];
if (value < 0) value = 0;
if (value > 1000) value = 1000;
mySlider.value = value;
myTextBox.text = [NSString stringWithFormat:#"%.1f", value];
if ([myTextBox canResignFirstResponder]) [myTextBox resignFirstResponder];
}
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
if (myTextBox)
{
if ([myTextBox canResignFirstResponder]) [myTextBox resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
[self.textField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (IBAction)changeGreeting:(id)sender {
self.username = self.myTextBox.text;
NSString *nameString = self.username;
if ([nameString length] == 0) {
nameString = #"World";
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[myTextBox resignFirstResponder];
return NO;
}
#end

Related

use of undeclared identifier 'prepareForSegue'

I'm having two issues with the below code. First, the userCategorySave Parse cloud function is supposed to run when the submit button is tapped, however there are no signs of it running in my logs.
The other problem is an error I'm getting that states use of undeclared identifier 'prepareForSegue'. I was under the impression that prepareForSegue was a standard part of an iOS app, and didn't need to be declared. Why is this class in particular giving me this error?
#import "CriteriaViewController.h"
#interface CriteriaViewController ()
#property (weak, nonatomic) IBOutlet UISegmentedControl *itemConditionSegment;
#property (weak, nonatomic) IBOutlet UISegmentedControl *itemLocationSegment;
#property (weak, nonatomic) IBOutlet UIButton *submitButton;
#end
#implementation CriteriaViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)itemConditionSegment:(id)sender{
UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
if (selectedSegment == 0) {
self.itemCondition = #"new";
}
else{
self.itemCondition = #"any";
}
}
- (IBAction)itemLocationSegment:(id)sender {
UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
if (selectedSegment == 0) {
self.itemLocation = #"US";
}
else if (selectedSegment == 1) {
self.itemLocation = #"WorldWide";
}
}
//add all the info to users respective new category object
- (IBAction)submitButton:(id)sender
{
if (self.minPrice.text.length > 0 && self.maxPrice.text.length > 0)
{
[PFCloud callFunctionInBackground:#"userCategorySave"
withParameters:#{#"categoryId": self.chosenCategory,
#"minPrice": self.minPrice.text,
#"maxPrice": self.maxPrice.text,
#"itemCondition": self.itemCondition,
#"itemLocation": self.itemLocation,}
block:^(NSString *result, NSError *error) {
if (!error) {
NSLog(#"Criteria successfuly saved.");
[self performSegueWithIdentifier:#"ShowMatchCenterSegue" sender:self];
}
}];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
#end
You did not close the } correctly.so add one brase in the above method prepare for seque.

Objective c - Getting text from a UITextfield after keyboard is dismissed

Another NEWBIE QUESTION:
I'm feeling pretty dumb right now. I haven't worked with UI text input for a very long time. So this is what I have so far. I have a view with a subview. I've wired up my IBOutlets for the UITextFields and I've wired the text fields back to the main view controller file owner for the delegate (not sure about that one). I happily build and run. I enter some text and when I click outside the text field my keyboard goes away. But when I exit my view I should be saving the values in each of the fields. But when I step through the code, my textfields (not the text but the fields themselves) are all nil.
So, obviously I've missed an important step here.
Calling saveUserSettings from the main view when user clicks to close the subview:
- (IBAction)closeButtonPressed:(UIButton *)sender {
[self.userSettingsView saveUserSettings];
[self dismissViewControllerAnimated:YES completion:nil];
}
The psychedelic colors are helping me see them during development. :-)
The selected view is a scrollview but it's not scrolling either. That's a different issue.
Here is the IDUtilityViewController code:
#interface IDUtilityViewController ()
#property (strong, nonatomic) IBOutlet IDAboutView *aboutView;
#property (strong, nonatomic) IBOutlet IDUserSettingsView *userSettingsView;
#property (strong, nonatomic) IBOutlet UIButton *aboutButton;
#property (strong, nonatomic) IBOutlet UIButton *userSettingsButton;
#end
#implementation IDUtilityViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.aboutView = [[IDAboutView alloc] init];
self.userSettingsView = [[IDUserSettingsView alloc] init];
[self userSettingsButtonPressed:self.userSettingsButton];
UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(hideKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];
}
- (void)hideKeyboard
{
[self.userSettingsView saveUserSettings];
[self.view endEditing:YES];
}
#pragma mark - IBActions
- (IBAction)closeButtonPressed:(UIButton *)sender {
//[self.userSettingsView saveUserSettings];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)aboutButtonPressed:(UIButton *)sender {
self.userSettingsView.hidden = YES;
self.aboutView.hidden = NO;
}
- (IBAction)userSettingsButtonPressed:(UIButton *)sender {
self.aboutView.hidden = YES;
self.userSettingsView.hidden = NO;
}
Here is the IDUserSettingsView.h:
#interface IDUserSettingsView : UIView
#property (nonatomic, strong) IBOutlet UITextField *userIDField;
#property (nonatomic, strong) IBOutlet UITextField *passwordField;
#property (nonatomic, strong) IBOutlet UITextField *ipAddressField;
#property (nonatomic, strong) IBOutlet UITextField *portNumberField;
#property (nonatomic, strong) IBOutlet UITextField *doorNameField;
#property (nonatomic, strong) IBOutlet UITextField *badgeNumberField;
- (void)saveUserSettings;
#end
Here is the IDUserSettingsView.m:
#import "IDUserSettingsView.h"
#interface IDUserSettingsView()
#property (nonatomic, strong) NSUserDefaults *standardUserDefaults;
#end
#implementation IDUserSettingsView
#synthesize userIDField = _userIDField;
#synthesize passwordField = _passwordField;
#synthesize ipAddressField = _ipAddressField;
#synthesize portNumberField = _portNumberField;
#synthesize doorNameField = _doorNameField;
#synthesize badgeNumberField = _badgeNumberField;
NSMutableString *emptyString = #"";
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.standardUserDefaults = [NSUserDefaults standardUserDefaults];
}
return self;
}
- (void)saveUserSettings
{
[self.standardUserDefaults setObject:self.userIDField.text forKey:#"isonos_userID"];
[self.standardUserDefaults setObject:self.passwordField.text forKey:#"isonos_password"];
[self.standardUserDefaults setObject:self.ipAddressField.text forKey:#"isonos_ipAddress"];
[self.standardUserDefaults setObject:self.portNumberField.text forKey:#"isonos_portNumber"];
[self.standardUserDefaults setObject:self.doorNameField.text forKey:#"isonos_doorName"];
[self.standardUserDefaults setObject:self.badgeNumberField.text forKey:#"isonos_badgeNumber"];
}
- (UITextField *)userIDField {
return _userIDField;
}
- (void)setUserIDField:(UITextField *)userIDField {
NSString *result = [self.standardUserDefaults stringForKey:#"isonos_userID"];
if (!result) result = emptyString;
_userIDField.text = [emptyString stringByAppendingString:result];
}
- (UITextField *)passwordField {
return _passwordField;
}
- (void)setPasswordField:(UITextField *)passwordField {
NSString *result = [self.standardUserDefaults stringForKey:#"isonos_password"];
if (!result) result = emptyString;
_passwordField.text = [emptyString stringByAppendingString:result];
}
- (UITextField *)ipAddressField {
return _ipAddressField;
}
- (void)setIpAddressField:(UITextField *)ipAddressField {
NSString *result = [self.standardUserDefaults stringForKey:#"isonos_ipAddress"];
if (!result) result = emptyString;
_ipAddressField.text = [emptyString stringByAppendingString:result];
}
- (UITextField *)portNumberField {
return _portNumberField;
}
- (void)setPortNumberField:(UITextField *)portNumberField {
NSString *result = [self.standardUserDefaults stringForKey:#"isonos_portNumber"];
if (!result) result = emptyString;
_portNumberField.text = [emptyString stringByAppendingString:result];
}
- (UITextField *)doorNameField {
return _doorNameField;
}
- (void)setDoorNameField:(UITextField *)doorNameField {
NSString *result = [self.standardUserDefaults stringForKey:#"isonos_doorName"];
if (!result) result = emptyString;
_doorNameField.text = [emptyString stringByAppendingString:result];
}
- (UITextField *)badgeNumberField {
return _badgeNumberField;
}
- (void)setBadgeNumberField:(UITextField *)badgeNumberField {
NSString *result = [self.standardUserDefaults stringForKey:#"isonos_badgeNumber"];
if (!result) result = emptyString;
_badgeNumberField.text = [emptyString stringByAppendingString:result];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
I've even tried just setting the controls straight with no values:
#import "IDUserSettingsView.h"
#interface IDUserSettingsView()
#property (nonatomic, strong) NSUserDefaults *standardUserDefaults;
#end
#implementation IDUserSettingsView
#synthesize userIDField = _userIDField;
#synthesize passwordField = _passwordField;
#synthesize ipAddressField = _ipAddressField;
#synthesize portNumberField = _portNumberField;
#synthesize doorNameField = _doorNameField;
#synthesize badgeNumberField = _badgeNumberField;
NSMutableString *emptyString = #"";
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.standardUserDefaults = [NSUserDefaults standardUserDefaults];
}
return self;
}
- (void)saveUserSettings
{
[self.standardUserDefaults setObject:self.userIDField.text forKey:#"isonos_userID"];
[self.standardUserDefaults setObject:self.passwordField.text forKey:#"isonos_password"];
[self.standardUserDefaults setObject:self.ipAddressField.text forKey:#"isonos_ipAddress"];
[self.standardUserDefaults setObject:self.portNumberField.text forKey:#"isonos_portNumber"];
[self.standardUserDefaults setObject:self.doorNameField.text forKey:#"isonos_doorName"];
[self.standardUserDefaults setObject:self.badgeNumberField.text forKey:#"isonos_badgeNumber"];
}
- (UITextField *)userIDField {
return _userIDField;
}
- (void)setUserIDField:(UITextField *)userIDField {
_userIDField = userIDField; // breakpoint here
}
- (UITextField *)passwordField {
return _passwordField;
}
- (void)setPasswordField:(UITextField *)passwordField {
_passwordField = passwordField;
}
- (UITextField *)ipAddressField {
return _ipAddressField;
}
- (void)setIpAddressField:(UITextField *)ipAddressField {
_ipAddressField = ipAddressField;
}
- (UITextField *)portNumberField {
return _portNumberField;
}
- (void)setPortNumberField:(UITextField *)portNumberField {
_portNumberField = portNumberField;
}
- (UITextField *)doorNameField {
return _doorNameField;
}
- (void)setDoorNameField:(UITextField *)doorNameField {
_doorNameField = doorNameField;
}
- (UITextField *)badgeNumberField {
return _badgeNumberField;
}
- (void)setBadgeNumberField:(UITextField *)badgeNumberField {
_badgeNumberField = badgeNumberField;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
Here is the View Hierarchy:
If you're calling "saveUserSettings" from your main view (and not your IDUserSettingsView), then it's likely the IDUserSettingsView has dismissed and all the outlet connections are long gone.
Why not copy the changed settings into some structure that gets sent/copied into your main view which you can then call "saveUserSettings" on when the user chooses to update his/her settings?
Or, make certain "saveUserSettings" gets called before your IDUserSettingsView dismisses (and everything in that view gets torn down and/or dealloc'd).
You probably messed up the IBOutlet connections, I bet they're not connected or connected to the wrong objects.
Try defining a setter method and putting a breakpoint on it to try and find where it's being set or perhaps cleared to nil:
- (void)setUserIDField:(UITextField *)field
{
_userIDField = field; // breakpoint here
}
(note: if you have ARC disabled you will need to retain the new value and release the old value).

Why Isn't My UITextField Wrapper Being Displayed In UITableViewCell?

The issue is that my UITextField wrapper class isn't getting the UITextField to appear within a UITableViewCell (however, a regular UITextField view works just fine):
Here is my custom UITextField:
Header:
#import <UIKit/UIKit.h>
#protocol TUTextFieldDelegate <NSObject>
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string;
- (BOOL)textFieldShouldClear:(UITextField *)textField;
- (void)textFieldDidBeginEditing:(UITextField *)textField;
- (void)textFieldDidEndEditing:(UITextField *)textField;
#end
#interface TUTextField : UIControl <UITextFieldDelegate>
#property (nonatomic, assign) BOOL fixedDecimalPoint;
#property (nonatomic, assign) id <TUTextFieldDelegate>delegate;
#property (nonatomic, assign) UIKeyboardType keyboardType;
#property (nonatomic, strong) NSString *placeholder;
#property (nonatomic, assign) UITextBorderStyle borderStyle;
#property (nonatomic, assign) BOOL adjustsFontSizeToFitWidth;
#property (nonatomic, assign) UITextFieldViewMode clearButtonMode;
#property (nonatomic, strong) NSString *text;
- (id)initWithTextField:(UITextField *)textField;
- (id)initWithFrame:(CGRect)frame;
#end
Implementation:
#import "TUTextField.h"
#interface TUTextField ()
#property (nonatomic, strong) UITextField *textField;
#end
#implementation TUTextField
- (id)initWithTextField:(UITextField *)textField
{
self = [super initWithFrame:textField.frame];
if (self) {
self.textField = textField;
_textField.delegate = self;
_fixedDecimalPoint = NO;
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.textField = [[UITextField alloc] initWithFrame:frame];
_textField.delegate = self;
[self addSubview:_textField];
_fixedDecimalPoint = NO;
}
return self;
}
- (void)setKeyboardType:(UIKeyboardType)keyboardType {
_textField.keyboardType = keyboardType;
}
- (void)setPlaceholder:(NSString *)placeholder {
_textField.placeholder = placeholder;
}
- (void)setBorderStyle:(UITextBorderStyle)borderStyle {
_textField.borderStyle = borderStyle;
}
-(void)setAdjustsFontSizeToFitWidth:(BOOL)adjustsFontSizeToFitWidth {
_textField.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth;
}
-(void)setClearButtonMode:(UITextFieldViewMode)clearButtonMode {
_textField.clearButtonMode = clearButtonMode;
}
-(void)setText:(NSString *)text {
_textField.text = text;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
[self addSubview:self.textField];
}
*/
- (void)viewDidLoad {
[self addSubview:_textField];
}
- (void)viewWillAppear {
[self addSubview:_textField];
}
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
if ([_delegate respondsToSelector:#selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
return [_delegate textField:textField shouldChangeCharactersInRange:range
replacementString:string];
}
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField {
if ([_delegate respondsToSelector:#selector(textFieldShouldClear:)]) {
return [_delegate textFieldShouldClear:textField];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if ([_delegate respondsToSelector:#selector(textFieldDidBeginEditing:)]) {
[_delegate textFieldDidBeginEditing:textField];
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
if ([_delegate respondsToSelector:#selector(textFieldDidEndEditing:)]) {
[_delegate textFieldDidEndEditing:textField];
}
}
#end
And here is the code to add my custom wrapper to the table view:
} else if (indexPath.row == 1) {
cell.textLabel.text = #"Tax Rate";
if (!_textField) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(220.0, 8.0, 60.0, 26.0)];
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.adjustsFontSizeToFitWidth = YES;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.keyboardType = UIKeyboardTypeDecimalPad;
textField.placeholder = kTaxRateDefault;
_textField = [[TUTextField alloc] initWithTextField:textField];
_textField.delegate = self;
// retrieve saved settings
_taxRate = [[SettingsSingleton sharedManager] taxRate];
if (![_taxRate isEqualToString:#""])
_textField.text = _taxRate;
}
UILabel *percentSign = [[UILabel alloc] initWithFrame:CGRectMake(285.0, 6.0, 20.0, 26.0)];
percentSign.text = #"%";
percentSign.backgroundColor = [UIColor clearColor];
[cell addSubview:_textField];
[cell addSubview:percentSign];
}
}
Any help appreciated!
I don't think this is the best way to extend a UITextField.
Instead of making an NSObject with a UITextField under it you should be saying something like:
Interface:
#interface UITextField (extendedUITextField) {
// Variables
}
//Methods
#end
Implementation:
#implementation UITextField (extendedUITextField)
// Method implement
#end
Hope this helps.

Incorrect UITextfield is being edited

I just finished a tutorial on making my own keypad. So I took that knowledge and made a real simple App that adds two numbers with my own keypad. It is just two numbers. But when I tap on one textfield, the other textfield gets edited! I have enclosed my code, any help will be much appreciated. And thanks to #spacious for all previous help.
#import "KeyPad2ViewController.h"
#interface KeyPad2ViewController ()
#property (nonatomic) BOOL userIsEnteringANumber;
#end
#implementation KeyPad2ViewController
#synthesize numberOne;
#synthesize numberTwo;
#synthesize result;
#synthesize keyPad;
#synthesize userIsEnteringANumber;
#synthesize currentTextField;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if ([numberOne isFirstResponder])
{
self.currentTextField = self.numberOne;
self.userIsEnteringANumber = NO;
}
else if ([numberTwo isFirstResponder])
{
self.currentTextField = self.numberTwo;
self.userIsEnteringANumber = NO;
}
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[numberOne setInputView:keyPad];
[numberTwo setInputView:keyPad];
numberOne.delegate = self;
numberTwo.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setNumberOne:nil];
[self setNumberTwo:nil];
[self setResult:nil];
[self setKeyPad:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (IBAction)buttonPressed:(UIButton *)sender
{
NSString *button = [sender currentTitle];
NSRange decimalpoint = [self.currentTextField.text rangeOfString:#"."];
if (self.userIsEnteringANumber)
{
if ([button isEqualToString:#"."] && decimalpoint.location != NSNotFound)
{
self.currentTextField.text = self.currentTextField.text;
}else
self.currentTextField.text = [self.currentTextField.text stringByAppendingString:button];
}else
{
self.currentTextField.text = button;
self.userIsEnteringANumber = YES;
}
}
- (IBAction)backspacePressed:(UIButton *)sender
{
if (self.userIsEnteringANumber)
{
int positionOfDigitBeforeLastOne = self.currentTextField.text.length -1;
if (self.currentTextField.text.length > 0)
{
self.currentTextField.text = [self.currentTextField.text substringToIndex:positionOfDigitBeforeLastOne];
}
if (self.currentTextField.text.length == 0)
self.currentTextField.text = #"";
}
}
- (IBAction)clearPressed:(id)sender
{
currentTextField.text = [NSString stringWithFormat:#""];
}
- (IBAction)enterPressed:(UIButton *)sender
{
[self hideKeyPad];
}
- (IBAction)signPressed:(UIButton *)sender
{
NSString *negativeNumber = #"-";
NSString *firstCharInDisplay = #"";
if (self.userIsEnteringANumber)
{
firstCharInDisplay = [self.currentTextField.text substringToIndex:1];
if ([firstCharInDisplay isEqualToString:#"-"])
{
self.currentTextField.text = [self.currentTextField.text substringFromIndex:1];
}else {
negativeNumber = [negativeNumber stringByAppendingString:self.currentTextField.text];
self.currentTextField.text = negativeNumber;
}
}
}
- (IBAction)add:(UIButton *)sender
{
float a = [[numberOne text] floatValue];
float b = [[numberTwo text] floatValue];
float c = a + b;
[result setText:[NSString stringWithFormat:#"%.2f", c]];
}
- (void)showKeyPad
{
[UIView beginAnimations:#"animateView" context:nil];
[UIView setAnimationDuration:0.3];
CGRect keypadview = CGRectMake(0, 270, 320, 190); // puts keyboard on screen
keyPad.frame = keypadview;
keyPad.alpha = 1.0;
[UIView commitAnimations];
}
- (void)hideKeyPad
{
[UIView beginAnimations:#"animateView" context:nil];
[UIView setAnimationDuration:0.3];
CGRect keypadview = CGRectMake(0, 640, 320, 190); // puts keyboard off screen
keyPad.frame = keypadview;
keyPad.alpha = 1.0;
[UIView commitAnimations];
}
#end
and my .h file is
#import <UIKit/UIKit.h>
#interface KeyPad2ViewController : UIViewController <UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *numberOne;
#property (weak, nonatomic) IBOutlet UITextField *numberTwo;
#property (weak, nonatomic) IBOutlet UILabel *result;
#property (strong, nonatomic) IBOutlet UIView *keyPad;
#property (weak, nonatomic) UITextField *currentTextField;
- (IBAction)buttonPressed:(UIButton *)sender;
- (IBAction)backspacePressed:(UIButton *)sender;
- (IBAction)clearPressed:(UIButton *)sender;
- (IBAction)enterPressed:(UIButton *)sender;
- (IBAction)octopusPressed:(UIButton *)sender;
- (IBAction)signPressed:(UIButton *)sender;
- (IBAction)add:(UIButton *)sender;
#end
Thanks to any and all help. This site is really the best!!
When your textFieldShouldBeginEditing: method is called, the first responder has not been set to the correct field yet. Replace the textFieldShouldBeginEditing: with textFieldDidBeginEditing: to fix this problem.

Text Box Picker

Im practicing using a picker to input values into a text field. Ive tried to adapt some code found on here to present a picker when text box is touched to fill out text field. The text boxes were built in code SOURCE and I would like to build the text boxes in IB. However this has stopped the presentation picker view, and presents only the keyboard now instead
Perhaps someone would point me in the right direction here. My code:
.h
#import <UIKit/UIKit.h>
#interface pick2 : UIViewController
<UIPickerViewDelegate, UIPickerViewDataSource> {
UIPickerView *locationsPicker;
UIToolbar *accessoryView;
UITextField *text1;
NSArray *locations;
}
#property (nonatomic, readonly) UIPickerView *locationsPicker;
#property (nonatomic, readonly) UIToolbar *accessoryView;
#property (strong, nonatomic) IBOutlet UITextField *text1;
- (void)onLocationSelection;
#end
.m
#import "pick2.h"
#interface pick2 ()
#end
#implementation pick2
#synthesize text1;
- (UIPickerView *)locationsPicker {
if ( locationsPicker == nil ) {
locationsPicker = [[UIPickerView alloc] init];
locationsPicker.delegate = self;
locationsPicker.dataSource = self;
locationsPicker.showsSelectionIndicator = YES;
}
return locationsPicker;
}
- (UIToolbar *)accessoryView {
if ( accessoryView == nil ) {
accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStylePlain
target:self
action:#selector(onLocationSelection)];
[accessoryView setItems:[NSArray arrayWithObject:doneButton]];
}
return accessoryView;
}
#pragma mark - Memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)onLocationSelection {
NSInteger row = [self.locationsPicker selectedRowInComponent:0];
( [text1 isFirstResponder] ); {
text1.text = [locations objectAtIndex:row];
[text1 resignFirstResponder];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - picker view delegate/datasource
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [locations objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component {
return [locations count];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
locations = [[NSArray alloc] initWithObjects:#"New York", #"Chicago", #"Memphis", #"California", #"Seattle",#"London",#"Paris", nil];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setText1:nil];
[super viewDidUnload];
}
#end
All you have to do is give the inputView of your UITextField as object of your pickerview.
text1.inputView = locationsPicker;
tapping on the UITextField will present the pickerview now.
Sorted this by using IB to build text boxes and
NSInteger selectedRow = [select selectedRowInComponent:0];
text1.text = [arrStatus objectAtIndex: selectedRow];
[text1 resignFirstResponder];
To retrive text value