Using a button in iOS [closed] - ios

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to learn how to get a button (in my case, a 'Cancel' button) to direct me back to the previous page it was on. I've got a button on my previous page that directs me to this page, and i want this button to take me back to the previous page and discard anything i had written on the page. My button on my first page pushes the view to this page through a modal connection. I know it would make sense to just use the simple modal connection for the Cancel button to get back to my original page, but I was hoping for a more elegant way to do this. Creating a custom view is a good idea i'm sure but I don't really know what to do there so.. haha but any suggestions would be greatly appreciated!
#import "AddEventViewController.h"
#import <QuartzCore/QuartzCore.h>
#interface AddEventViewController ()
#property (weak, nonatomic) IBOutlet UITextField *textField1;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak, nonatomic) IBOutlet UITextField *textField3;
#property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
#property (weak, nonatomic) IBOutlet UINavigationBar *addEventTitleBar;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *cancelButton;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
#property (weak, nonatomic) IBOutlet UITextView *myTextView;
- (IBAction)textFieldReturn:(id)sender;
#end
#implementation AddEventViewController
#synthesize textField1, textField2, textField3, myTextView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)textFieldReturn:(id)sender;
{
[sender resignFirstResponder];
}
- (void)viewDidLoad
{ // Do any additional setup after loading the view.
[super viewDidLoad];
self.textField1.delegate = self;
textField1.delegate = self;
self.textField2.delegate = self;
textField2.delegate = self;
self.textField3.delegate = self;
textField3.delegate = self;
[myTextView.layer setCornerRadius:10.0f];
[myTextView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[myTextView.layer setBorderWidth:1.5f];
[myTextView.layer setShadowColor:[UIColor blackColor].CGColor];
[myTextView.layer setShadowOpacity:0.002f];
[myTextView.layer setShadowRadius:3.0f];
[myTextView.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan: (NSSet *) touches withEvent: (UIEvent *)event
{
if (textField1)
{
if ([textField1 canResignFirstResponder]) [textField1 resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
if (textField2)
{
if ([textField2 canResignFirstResponder]) [textField2 resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
if (textField3)
{
if ([textField3 canResignFirstResponder]) [textField3 resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == textField1)
{
[textField1 resignFirstResponder];
}
else if (textField == textField2)
{
[textField2 resignFirstResponder];
}
else if (textField == textField3)
{
[textField3 resignFirstResponder];
}
return YES;
}
-(void)addCancelButton
{
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel"style:UIBarButtonSystemItemAction target:self action:#selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelButton;
}
-(void)cancel:(id)sender
{
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popViewControllerAnimated:NO];
}
#end
Fixed the issue!

You could solve it like this:
- (void)addCancelButton{
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel"
style:UIBarButtonSystemItemCancel target:self action:#selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelButton;
}
- (void)cancel:(id)sender{
//If presented
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
//If pushed
[self.navigationController popViewControllerAnimated:NO];
}
Where the code in AddCancelButton can be moved to viewDidLoad or somewhere appropriate. And you might want to edit how the view is removed depending on how it was added (pushed, presented etc.)

Related

i am able to hide 1st texbox's keyboard but not for the 2nd textbox in ios

Hi i am trying to hide the keyboard when it appears while typing. I have successfully done the code for the 1st textbox which is username_textbox, but when i do the same code for 2nd textbox which is password_textbox keyboard does not hide.
Can anyone help me out in this how to hide keyboards when there are multiple textboxes.
MY code is:
ViewController.h
//#interface ViewController : UIViewController
//
//#end
#interface ViewController : UIViewController<UITextFieldDelegate>
#property (strong, nonatomic) IBOutlet UITextField *usernameTextbox;
#property (strong, nonatomic) IBOutlet UITextField *passwordTextbox;
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self navigationController]setNavigationBarHidden:YES animated:YES ];
[self.usernameTextbox setDelegate:self];
[self.passwordTextbox setDelegate:self];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.usernameTextbox resignFirstResponder];
return YES;
}
-(BOOL)textField2ShouldReturn:(UITextField *)textField
{
[self.passwordTextbox resignFirstResponder];
return YES;
}
Try this
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
// [self.usernameTextbox resignFirstResponder];
// [self.passwordTextbox resignFirstResponder];
[self.view endEditing:YES];
return YES;
}
Try this
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}

UITextField won't return and text field can't be changed. How do I fix this?

I am having problems trying to get the keyboard to go to the next field or return when the return key is pressed, my code is:
#interface LoginViewController ()
#property (weak, nonatomic) IBOutlet UIButton *loginButton;
#property (weak, nonatomic) IBOutlet UITextField *userField;
#property (weak, nonatomic) IBOutlet UITextField *passwordField;
#property (strong, nonatomic) UITextField *textField;
#end
#implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidLayoutSubviews
{
[self.userField becomeFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)tapLogin:(id)sender {
NSLog(#"login");
}
#pragma mark - UITextFieldDelegate methods
// for return and next
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
if (textField == self.userField) {
[self.passwordField becomeFirstResponder];
}
else if (textField == self.passwordField) {
[self tapLogin:nil];
}
return YES;
}
The cursor beings in the userField but hitting the return key does nothing, if I manually tap on another field i.e the password one this also won't do anything. The cursor is stuck in the username field. I have implemented the protocol in my header file and also set the text fields as delegates in the interface builder. Could someone help please?
Try this,
Remove [self.userField becomeFirstResponder]; method from viewDidLayoutSubviews ie, remove the below method
- (void)viewDidLayoutSubviews
{
[self.userField becomeFirstResponder];
}
and add
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.userField becomeFirstResponder];
}

Can't change label.text and don't know why

I want to change label.text but when I do it and check it with a NSLog it returns me a (null).
Here's my code:
NextViewController.h
#interface NextViewController (){
NSTimer *timerTen;
NSInteger countDown;
NSString *timer;
}
#end
#implementation NextViewController
static UILabel *lblTest;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)startCountDown{
countDown = 10;
timerTen = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(dismissView) userInfo:nil repeats:YES];
}
-(void)dismissView{
timer = [NSString stringWithFormat:#"%ld", (long)countDown];
_lbl_countDown.text = timer;
NSLog(#"\nCountDown: %#\n", self.lbl_countDown.text);
countDown--;
if (countDown <= 0) {
SectionViewController *sectionView = [[SectionViewController alloc] init];
[sectionView.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}
}
Then I have a XIB file with a label and more things, so I've used a prop right there in the .h to change it from other classes, but I can't change it.
NextViewController.h
#import <UIKit/UIKit.h>
#interface NextViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *lbl_section;
#property (strong, nonatomic) IBOutlet UILabel *lbl_nextSection;
#property (strong, nonatomic) IBOutlet UILabel *lbl_countDown;
-(void)startCountDown;
#end
Hope anyone can help me cause I don't know what is happening here.
Thanks.
Call your method in ViewDidLoad or ViewWillAppear
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self startCountDown]
}
OR
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self startCountDown]
}
Try to call the function first using [self startCountDown] in the ViewDidLoad method
if the problem persist:
Try to use this : [_lbl_count setText#"myText"];
In the Identity Inspector, click on the label uncheck the 'Static Text' and check 'Enabled' and 'User Interaction Enabled'
Finally check that your variable timer is not null after your initialization.
timer = [NSString stringWithFormat:#"%ld", (long)countDown];
Hope that will be helpfull
I wrote this code to use a button tap to start a countdown from 10 to a segue:
In my h:
#property (strong, nonatomic) IBOutlet UILabel *countdownCounter;
#property (strong, nonatomic) IBOutlet UIButton *countdownStarter;
In my m:
static NSTimer *timer;
static int remainingCounts;
.
.
-(void)countDown
{
if (--remainingCounts == 0)
{
[timer invalidate];
timer = nil;
[self performSegueWithIdentifier:#"FromStartToBalancer" sender:self];
}
else
{
NSString * holdText = [NSString stringWithFormat:#"%d", remainingCounts];
[self.countdownCounter setText:holdText];
}
}
- (IBAction)goToBalancerPressed:(UIButton *)sender
{
self.countdownStarter.userInteractionEnabled = NO;
self.countdownStarter.alpha = .3;
remainingCounts = 10;
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(countDown)
userInfo:nil
repeats:YES];
}

UIScrollView not responding to touch

My UIScrollView is not responding to touch events, nor is my touchesBegain method being called for my UIViewController. (Also the text on my buttons are distorted on one and not shown on the other)
In Storyboard I added the ScrollView to the UIViewController and added my UITextFields and UIButtons to the ScrollView
Here is the code:
#import <UIKit/UIKit.h>
#interface RefineSearchViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>
{
IBOutlet UIScrollView *scroller;
}
#property (strong, nonatomic) IBOutlet UITextField *nameField;
#property (strong, nonatomic) IBOutlet UITextField *targetField;
#property (strong, nonatomic) IBOutlet UITextField *vendorField;
#property (strong, nonatomic) IBOutlet UITextField *CATField;
#property (strong, nonatomic) IBOutlet UITextField *clonalityField;
#property (strong, nonatomic) IBOutlet UITextField *sourceOrganismField;
-(IBAction) textFieldReturn: (id) sender;
#import "RefineSearchViewController.h"
#import "DBHandler.h"
#interface RefineSearchViewController ()
#end
#implementation RefineSearchViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[scroller setScrollEnabled:YES];
// set the content size to be the size our our whole frame
//scroller.frame = CGRectMake(74, 261, 620, 354);
[scroller setContentSize:CGSizeMake(2000, 2000)];
[scroller setCanCancelContentTouches:NO];
[super viewDidLoad];
// Do any additional setup after loading the view.
self.targetField.delegate = self;
self.nameField.delegate = self;
self.vendorField.delegate = self;
self.clonalityField.delegate = self;
self.sourceOrganismField.delegate = self;
self.CATField.delegate = self;
}
-(void) viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// If you are going to conduct a refine search
if ([[segue identifier] isEqualToString:#"Refine"])
{
DBHandler *handler = [[DBHandler alloc]init];
//Run searches on each of the parameter that aren't empty
NSString *nameParameter = _nameField.text;
if (![nameParameter isEqualToString:#""])
{
[handler search:0 andInput:nameParameter];
}
NSString *targetParameter = _targetField.text;
if(![targetParameter isEqualToString:#""])
{
[handler search:1 andInput:targetParameter];
}
NSString *vendorParameter = _vendorField.text;
if (![vendorParameter isEqualToString:#""])
{
[handler search:2 andInput:vendorParameter];
}
NSString *catParameter = _CATField.text;
if (![catParameter isEqualToString:#""])
{
[handler search:3 andInput:catParameter];
}
NSString *clonalityField = _clonalityField.text;
if (![catParameter isEqualToString:#""])
{
[handler search:4 andInput:clonalityField];
}
NSString *sourceField = _sourceOrganismField.text;
if (![sourceField isEqualToString:#""])
{
[handler search:5 andInput:sourceField];
}
//recursive implementation
for (int i = 0; i < 6 ; i++)
{
}
//We shouldn't clear the text fields here in my personal opinion because they apply to the search until you return to the homescreen and reset what is the
//current "working database"
}
//if you are going to cancel the refine search, simply go back to the previous screen
else if ([[segue identifier] isEqualToString:#"Cancel"])
{
//Do Nothing
//but more importantly....
//....clear Text Fields
_nameField.text = #"";
_targetField.text = #"";
_vendorField.text = #"";
_CATField.text = #"";
_clonalityField.text = #"";
_sourceOrganismField.text = #"";
}
}
//make that stubborn keyboard go away whenever you touch the background
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_nameField resignFirstResponder];
[_targetField resignFirstResponder];
[_vendorField resignFirstResponder];
[_CATField resignFirstResponder];
[_clonalityField resignFirstResponder];
[_sourceOrganismField resignFirstResponder];
}
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
}
//following code was taken and tweaked from stack overflow
//- (void)textFieldDidBeginEditing:(UITextField *)textField
//{
// [self animateTextField: textField up: YES];
// NSLog(#"YO");
//}
//
//
//- (void)textFieldDidEndEditing:(UITextField *)textField
//{
// [self animateTextField: textField up: NO];
//}
//
//- (void) animateTextField: (UITextField*) textField up: (BOOL) up
//{
// const int movementDistance = 216; //height of the keyboard
// const float movementDuration = 0.3f; // duration of the animation
//
// int movement = (up ? -movementDistance : movementDistance);
//
// [UIView beginAnimations: #"anim" context: nil];
// [UIView setAnimationBeginsFromCurrentState: YES];
// [UIView setAnimationDuration: movementDuration];
// self.view.frame = CGRectOffset(self.view.frame, 0, movement);
// [UIView commitAnimations];
//}
#end
Make sure your scrollView's delegate is set properly in storyboard and scrollView's userInteractionEnabled is set.

How can I show a UIPickerView when I hit my UITextField?

I have found a lot of sample code from internet, but also doesn't work.... anyone can tell me what's wrong of my coding below? thanks a lot. SOS
//My storeboard screen
http://imageupload.org/en/file/209300/03.jpg.html
//This is PickerViewTest.h
#interface InputRound : UIViewController<UITextFieldDelegate>
{
UIPickerView *pvPickerTest;
NSMutableArray *aryMaster;
}
#property (nonatomic, retain) IBOutlet UIPickerView *pvPickerTest;
#property (nonatomic, retain) NSMutableArray *aryMaster;
#end
//This is PickerViewTest.m
#interface InputRound ()
#end
#implementation PickerViewTest
#synthesize pvPickerTest, aryMaster;
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
aryMaster = [[NSMutableArray alloc] init];
[aryMaster addObject:#"User01"];
[aryMaster addObject:#"User02"];
[aryMaster addObject:#"User03"];
}
-(NSInteger)numberOfComponentsInPickerView:(NSInteger)component
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(NSInteger)component
{
return [aryMaster count];
}
-(NSString *) pickerView:(UIPickerView *)picker titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [aryMaster objectAtIndex:row];
}
-(void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Show UIPickerView
pvPickerTest.frame = CGRectMake(0, 500, pvPickerTest.frame.size.width, pvPickerTest.frame.size.height);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.50];
[UIView setAnimationDelegate:self];
pvPickerTest.frame = CGRectMake(0, 200, pvPickerTest.frame.size.width, pvPickerTest.frame.size.height);
[self.view addSubview:pvPickerTest];
[UIView commitAnimations];
return NO;
}
#end
Don't try and reinvent the wheel by rolling your own appearance animation to mimic the built in one. Set the picker view as the input view for your text field, and the system will do the animation for you:
textField.inputView = pickerView;
When you begin editing the text field, the picker is animated on screen for you. See my answer here for more details, including adding a toolbar on top with a "Done" button.

Resources